简体   繁体   中英

Call to undefined function Laravel

I have problem when I'm checking if collection is empty or not, Laravel gives me error

"Call to undefined method Illuminate\\Database\\Query\\Builder::isEmpty()".

Tho it work in other Controller, but when controller is in Sub folder is suddenly stops working.

Here is my code:

$group = UserGroup::where('id', $request->group_id)->first();
    if($group->isEmpty()){ // I get error from here
      return redirect()->back();
    }

One of the most popular way of debugging in PHP still remains the same – showing variables in the browser, with hope to find what the error is. Laravel has a specific short helper function for showing variables – dd() – stands for “Dump and Die” , but it's not always convenient. What are other options?

Note the below mentioned methods are to find where our class fails and what are all the conditions that are available after our query executes. What is our expected result before printing it. This methods are the best methods to find out the error as required by is.

First, what is the problem with dd()? Well, let's say we want to get all rows from DB table and dump them:

$methods = PaymentMethod::all();
dd($methods);

We would see like this:

在此处输入图片说明

But you get the point – to see the actual values, we need to click three additional times, and we don't see the full result without those actions. At first I thought – maybe dd() function has some parameters for it? Unfortunately not. So let's look at other options:

var_dump() and die():

Good old PHP way of showing the data of any type:

$methods = PaymentMethod::all();
var_dump($methods);
die();

What we see now:

在此处输入图片说明

But there's even more readable way.

Another PHP built-in function print_r() has a perfect description for us: “Prints human-readable information about a variable”

$methods = PaymentMethod::all();
print_r($methods);
die();

And then go to View Source of the browser… We get this:

在此处输入图片说明

Now we can read the contents easily and try to investigate the error.

Moreover, print_r() function has another optional parameter with true/false values – you can not only echo the variable, but return it as string into another variable. Then you can combine several variables into one and maybe log it somewhere, for example.

So, in cases like this, dd() is not that convenient – PHP native functions to the rescue. But if you want the script to literally “dump one simple variable and die” – then dd($var) is probably the fastest to type .

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