Search code examples
phplaravellaravel-blade

Empty or null variables in Laravel blade


I make two arrays (A1 & A2) in the server side by result of ->paginate(20) and send them to the view via two variables. Depending on contents some times all the first 20 posts is based on the array A1, so the 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 only to return 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 .


Solution

  • 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'));