简体   繁体   中英

Laravel Eloquent empty() function returns true for $request->url when there is a value

I have a request that contains a url link that a user types in and submits(in Laravel).

SomeRequest ▼
  +request: ParameterBag ▼
    #parameters: array:4 ▼
      "title" => "cake"
      "url" => "www.someurl.com"

In my controller, when I call empty($request->url) it returns true even though it is not actually empty. I have tried searching for an answer to this predicament to no avail.

Thanks.

The problem is that $request->url isn't a normal property. Internally the magic method __get() is called, which then returns the value from the parameter bag over a few other methods.

empty() doesn't know that and just checks (the same way as isset() ) if the property exists. That's why you get false even though you can access url .

The best solution is probably to check with has() :

$request->has('url'); // returns true

Note that there's a way this could be "fixed" in the framework. That is by implementing the magic method __isset() which get's called when an empty or isset check is run.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM