Call to undefined function Laravel - php

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.

Related

how to use DD() method in Laravel projects?

I know that for some it might be stupid or funny question (but I am newbie) but I need to find know how to properly use DD() method in laravel projects.
For example - I have got tasks to debug some code and functionality in my project (PHP laravel). And it always takes me for ever to find the exact file or folder or code where the problem is.
My mentor says to use DD() method to find things faster (but for learning purposes he didn't explain me a lot about how to actually use it and said to find out my self), but said that I should start with Route (we use backpack as well for our project). So after finding Route (custom.php file) which controller connects to my required route what should I do next? How do I implement dd() method (or as my mentor says dd('call here') method) to fast find what I should be looking for to solve my problem and complete my task? Where should I write this dd() and how should I write it?
Thank you for the answer in advance!
for example I have a:
public function create(): View
{
return view('xxxxxx. \[
//
//
\]);
}
and if I put dd() anywhere in the code, I get error message in my URL :(
first of all ,in Laravel we use dd() before return in order to read any variable.
in controller we often use two kinds of variables : collection(which we get its members via foreach) or singular variable (we get it via its name)for example:$var = 1; dd($var).
notice:
if you are using ajax response you will not be able to see dd() results in page ,you can see the result via network tab in your browser (if u inspect your page).
dd stands for "Dump and Die."
Laravel's dd() function can be defined as a helper function, which is used to dump a variable's contents to the browser and prevent the further script execution.
Example:
dd($users,$variable1,$var2);
You can use dd() in blade
#foreach($users as $user)
#dd($user)
OR
{{dd($user)}}
#endforeach
#dd($var1)
You can read this article, the have more example and comparison
https://shouts.dev/articles/laravel-dd-vs-dump-vs-vardump-vs-printr-with-example
As Laravel is following model-view-controller or MVC design pattern. First go to the route and check which controller is called in the URL with the related URL.
Then go to the controller. **dd**() function is basically a dump and die. you also can do this by **print** or **echo** function too.
Lets assume that I have a controller name ProductController where I have method name index.From where I need to show a list of products in a table.
// in controller
public function index()
{
$products = Products::all();
// here you think ,I need to check whether I am getting the output or
not.
dd( $products );
//Or echo $products;
return view ('product.list',compact('products'));
}
let's suppose you are getting everything but in view when you loop through the products you declare the wrong variable name or mistakenly do some spelling mistakes. and want to see the result.
In view just do the dd() method by the following way:
{{ dd($products) }}

PHP Prophecy ->reveal() method - should I put the expectations (like "willReturn", "ShouldBeCalled") before or after it?

Working with PHP Prophecy now. I have two codes samples:
One:
$aProphecy = $this->prophesize(A::class);
$aProphecy->someMethod()->willReturn([]);
//now can be used:
$aProphecy->reveal();
Two
$aProphecy = $this->prophesize(A::class);
$aProphecy->reveal();
$aProphecy->someMethod()->willReturn([]);
I can't understand which is the correct way, and why?
The order of your examples is not relevant at this point because both cases will be evaluated.
However, I prefer the first variant, because it is clearer what is expected from $aProphecy.
The important thing to notice is that your code isn't checking anything as you need to inject $aProphecy to another object and reveal it there:
$aProphecy = $this->prophesize(A::class);
$aProphecy->someMethod()->willReturn([]);
$bObject = new B($aProphecy->reveal());
$bObject->methodWhichCallSomeMethodInside();
// check if someMethod was called exactly once
$aProchecy->someMethod()->shouldBeCalled();

Empty or null variables in Laravel blade

I make two arrays (A1 & A2) in server side by result of ->paginate(20) and send theme to index blade via two variables. depended on contents some times all the first 20 posts is based of A1 array, so page returns error Undefined variable: A2 .
Even while A2 is completely null (and not only because of pagination), I want to handle it in blades to only returns empty and not errors.
I tried #if($A2) , #if(!is_null($A2)) , #empty checks on blade but still same error occurs.
Also i make $A2=""; on sever side before operations and then page returns Trying to get property of non-object .
It sounds like your blade page has multiple places where the $A2 variable is being called. You can try to go through and find all of them and preceed them with an if check such as #if(isset($A2) { do something with $A2 }
But, the easier approach, and perhaps better for readibilty and future code might be to initialise the variable to whatever type of collection it is on your controller. You had the right idea with $A2="";, but that is a string, and your code on the blade page is looking for an object (you probably have something like $A2->field called).
Here is a simplistic example - you can clean this up, but hopefully it makes it easy to understand. On your Controller something like this:
$A2 = MyModel::find($someId);
if(!isset($A2)){
$A2 = new MyModel();
}
Then make sure to send through to your blade page as at least an initialised model object.
return view('page.pages', compact('A2'));

How to check the whole chain of relational chain without check each method separately?

I often get an FatalErrorException that says Call to a member function method() on null. This happens mostly when I use (in blade) long chained sentences where one among them (models) is null. For example:
$file->owners()->first()->categories()->first()->title
so when for example here categories returns null I get this exception. I have to check each method one by one. I can't check them at a time like:
!empty($file->owners()->first()->categories()->first()->title)
!is_null($file->owners()->first()->categories()->first()->title)
isset($file->owners()->first()->categories()->first()->title)
count($file->owners()->first()->categories()->first()->title)
I still get the exception by using these, because (I guess) before getting the final parameter (here 'title') the process goes trough all methods and before it can't get to the final one the exception comes. Actually in controllers this could be guidable to make all these checks but in blade this does not come so relevant to me. Besides, this is a loop. So I am looking how I could do this check at once.
Well if you get null from the first first() call you cannot continue the method chaining. You can always use try ... catch:
try {
$file->owners()->first()->categories()->first()->title
} catch (\Exception $e) {
// do on fail
}
I'd recommend using View Presenter in your project. It really helps you to keep your code clean by moving all extra logic from your views and put it in a dedicated presenter class.
Watch this laracasts video to learn more.

Intercept and change function or method parameter value in error handler

In this comment in the PHP manual, a user suggested a class which would implement an error handler capable to implement primitive type hinting for PHP.
I understand how that class operates, however, I would like to know if it is possible to bring it to another level: instead of only checking the argument value to see if it matches the "typehint", would it be possible to replace the value with another one if it does match, and how?
I was thinking about something along the line of:
if(gettype($funcValue) == $typeHint) {
// here replace $funcValue, for example $funcValue = new Example($funcValue);
}
and then have the function call proceed with the new value?
I have searched the manual but found nothing which could allow me to "hook" in the parameters' values, but it could be there and I simply didn't find it.

Categories