This is a really odd error. In my blade view:
<?php //dd($site); ?>
#if($site==='site1')
On the second line #if($site==='site1') I get a Undefined variable: site error. But if I uncomment out the dump and die I get the $site variable set. It's literally on the very next line that it tells me it doesn't have a set $site variable in blade. Is my syntax wrong on the if statement?
It looks correct to me, the documentation gives:
#if (count($records) === 1)
I have one record!
#elseif (count($records) > 1)
I have multiple records!
#else
I don't have any records!
#endif
Adding a space between #if and the first paren ( made no difference.
I tried clearing the view cache but that made no difference too. Every other change gets registered, for example if I remove the $ that prepends the variable name I get an undefined constant error. I'm developing locally.
I'm at a complete loss because even though the variable is three levels deep in blade I am passing it correctly and I confirmed it with the dump and die. The conditional just won't pick it up.
I pass it into the view like this:
#component('pages.common.component.mycomponent',['site'=>$site])
#endcomponent
And one more level up like this:
#component('pages.common.parent.mycomponent',['site'=>'site1'])
#endcomponent
Any ideas I would be very grateful for!
EDIT:
The dd() call outputs:
"site1"
As a string.
The answer was later in the 2nd level (parent to the component in which I had the error) there were TWO declarations to this third component, one of which was not passing the $site variable. Of course, because I was using an inline dd() method of debugging in the third component it didn't make sense at first, as it hit the first declaration but not the second.
What helped me was calling the render method on the entire view and outputting it as a string, so I could see it was there in the first declaration but not in the second.
So in the controller, instead of:
return view('pages.routes.parent', $params);
I did:
dd(view('pages.routes.parent', $params)->render()); to get the entire view as one string output to trace where I was missing the data. Inspecting the storage compiled views didn't help as they are partials particular to each component or view.
Note for this to work I had to wrap the #if conditionals in another #if conditional, checking if the $site variable was isset().
Hope this can help someone else in the future.
Related
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) }}
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'));
I need to pass the value returned from {[item.document_type]} inside of a Laravel lang associaction #lang() in a blade file but get an undefined variable error in my browser.
{[item.doucument_type]} returns a string that is the address needed by #lang().
However when it is inside the brackets it throws error below, it doesn't work with $ prefix.
The purpose here is internationalization.
Desired outcome:
{[item.filename]} - #lang('app_name.otherlanguagefile'): #lang({[item.document_type]})
Error: Use of undefined constant item - assumed 'item' (this will throw an Error
in a future version of PHP)
The error doesn't throw if {[item.document_type]} is outside #lang()
Thanks in advance.
#lang expects a string, but you're passing {[item.document_type]} which is not a string (it's not quoted) and not a variable, so PHP is trying to interpret it as a constant. That's where the error Use of undefined constant is coming from (note that the error says undefined constant, not undefined variable).
{[]} is not a blade tag. Are you using another templating framework (such as javascript) in addition to blade, or are you trying to display the literal brackets to the user, or is this a mistake?
I suspect you want something like #lang($item['document_type']) or #lang($item->document_type), assuming item is a PHP variable being passed to your view.
If item is a javascript variable, then you cannot access it from your blade template and what you are trying to do is impossible; you will need a completely different approach.
If you want the brackets displayed to the user, then you need something like {[#lang(...)]} in your blade view. If it's not a variable, then perhaps you want {[#lang('item.document_type')]}
use language file parameter with two ways in your laravel blade file.
In your file.php inside language folder
<?php
return [
'variable' => 'this is test message'
];
?>
Laravel blade file
{{ #lang('file.variable') }}
or
{{ trans('file.variable') }}
Your output will be
this is test message
In your case please use {{ }} blade engine brackets for laravel.
I hope it helps.
You don't need curly braces if you're passing a parameter to a blade directive, such as #lang($variable).
{{ $item->filename }} - #lang($app_name->otherlanguagefile): #lang($item->document_type)??
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.
I am trying to pass data from my controller to my view, but am getting an undefined variable error. usersID is a column in my MySQL table.
Here is the code in my controller
$arrayWithCount = DB :: table("users_has_activities")
-> where("usersID", "=", 19)
-> pluck("usersID");
$countNumber = sizeof($arrayWithCount);
return view('pages.progress', ['countNumber' => $countNumber]);
I have also tried the following return statement without any success
return view::make('pages.progress') -> with('countNumber', $countNumber);
I have also tried reversing the puck and where clauses without any success, I didn't have high hopes that reversing them would fix the problem but thought I would try it any way. Below is the relevant code in the blade file.
<?php echo $countNumber; ?>
This is the error I am currently getting
Undefined variable: countNumber
You code looks fine, if dd() doesn't stop execution of the controller, then another controller is executing. So double check your routes and controllers.
First sizeof should be sizeOf, and is simply an alias for count(). Most people would prefer count over sizeOf as sizeOf (in many languages) would indicate something related to size on disk.
Anywho, being that pluck returns a collection, you have access to count() directly from the collection.
You can probably simply do something like:
$countNumber = $arrayWithCount->count();
Sidenote: Unless there is a particular reason why you are using <?php ?>, in blade, it would be preferred to use {{ and }}.
I had all the controller code in a method I wasn't calling, so the variable was never passed to the blade file. The method was set up to be called on a button press, after fixing that everything works. Thanks Alexey for the help.