Laravel undefined variable when trying to pass data to view - php

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.

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) }}

How to shuffle and paginate data with laravel

I want to shuffle and paginate data in laravel.
when I use this code :
`$questions = Question::where("exam_id",$exam->id)->shuffle()->paginate(1);`
gives me this error : BadMethodCallException
Call to undefined method Illuminate\Database\Eloquent\Builder::shuffle()
and when I use this code:
$questions = Question::where("exam_id",$exam->id)->paginate(1)->shuffle();
in dd($questions = Question::where("exam_id",$exam->id)->paginate(1)->shuffle());gives me a collection that has the first item and other items don't exist. And there is also no paging information.And when I don't use dd() gives me this error : Method Illuminate\Database\Eloquent\Collection::links does not exist. While I use $questions->links() in the
view.
When I use this code :
$questions = Question::where("exam_id",$exam->id)->get()->shuffle()->paginate(1);
Gives me this error : Method Illuminate\Database\Eloquent\Collection::paginate does not exist.
And when I use this code :
$questions = Question::where("exam_id",$exam->id)->inRandomOrder()->paginate(1);
It works, but the data is repeated on later pages. For example, the data on the first page may be repeated on page seven or other pages.
In fact, I want the data to be sorted by random And then paginated so that when a data is loaded on one page not repeated on subsequent pages.
please help me!!Thanks
I was facing this same problem and solved it by adding the shuffle()->all() methods to the collection variable in the view file, which seems to work perfectly.
Once you pass the variable to the view to loop over using a foreach I added the following:
$rows->shuffle()->all()
So my foreach loop looks like:
foreach($rows->shuffle()->all() as $row){ ... }
The rows on the front end when loaded using ajax still work as they should with the paginator since the collection is untouched and the selection of the next rows is correctly loaded and then shuffled, meaning there are no duplicates.

Laravel Blade Undefined Variable Error But The Variable Is Defined

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.

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

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.

Categories