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'));
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) }}
If possible..how would this be done? Laravel 5.5
route('section.category.subcategory',$subcategory->id)
must output (routes/web.php has the get:: set as this too)
/section/{parent_slug}/{subcategory_slug}
I could easily do
route('section.category.subcategory',[
'subcategory_slug' => $subcategory->slug,
'parent_slug'=>$parent->slug
]
);
but I'm trying to avoid having to declare those things all the time.
I thought getRouteKeyName in model would be first place to go to, but it binds to only one variable as far as I could find.
RouteHandler isn't the place to do anything either because it reads the url, not outputs it right?
I'm assuming in some file that I don't know about I will have to set this sort of logic.
if(requested_route is section.category.subcategory)){
// get the parent_id of ID provided,
// get parent's slug
// build the url.
}
Even better, I think I could do a left join when pulling the list of subcategories, so I have $subcategory->parent_slug instead of going for $parent->slug. This way
route('section.category.subcategory',[$subcategory])
has all the variables it needs to work with.
I think for this helper would be a good choice so you could create url like this:
route('section.category.subcategory',build_category_parameters($subcategory))
and you can create function like this:
function build_category_parameters($subcategory)
{
// here any logic that is needed
// here return array something like this
return [ 'subcategory_slug' => $subcategory->slug,
'parent_slug'=> $subcategory->parent->slug
];
}
If you don't have helper file already you can create one using this way Laravel - require php script in a service provider
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.
This is probably very easy to do, but I can't seem to get my head around it right now. Let's say in a component in a cakephp application, I have a variable my_model, which contains the model of the corresponding controller that is currently using the component like:
function TestComponent extend Object
{
var $my_model; // can be either User, or Person
function test()
{
$myModelTemp = $this->my_model;
$model = $myModelTemp != 'User' ? $myModelTemp.'->User' : 'User';
$this->$model->find('all');
}
}
As you can see above in my function test() what I'm trying to do is call the correct model based on the value of my_model. So based on the condition, my query will be either:
$this->Person->User->find('all');
Or
$this->User->find('all');
When I do it like I did above, I get an error saying Fatal error: Call to a member function find() on a non-object. In order words, that error means Person->User is not an object (so, it is considered as a string).
What you're saying could be true, however, it can refer to any part of the call.
So either Person or User could be invalid, or together they causes the error. Hard to say.
Try dumping the individual objects using var_dump();
So try:
<?php
echo "<pre>";
var_dump(is_object($this->Person));
var_dump(is_object($this->User));
echo "</pre>";
?>
to determine where you're code goes wrong.
To be clear, that return value needs to be true for it to be an object.
The one that returns false is the likely culprit.
Should your question refer to the correct way to reference an object, an object is basically an array. For example:
<?php
$obj = (object) array("this", "my_function");
?>
The above example casts the array as an object. However, using multiple layers might prove to be more difficult than you'd expect.
Generally, it looks like you might be going about this all wrong. Obviously you want the models to be dynamic, but then you're hard-coding things which defeats the whole point of it being dynamic in the first place.
It also seems like you might be violating the principals of CakePHP and MVC by doing all this in a component. I'm not sure this component should really be manipulating models or assuming which models are currently in use.
However, if you want to evaluate a string as an actual object, you can wrap it in { ... } (this is valid standard PHP syntax, not Cake-specific code).
Try this:
$modelName = $this->my_model;
$model = ($modelName != 'User') ? $this->{$modelName}->User : $this->User;
$model->find('all');
Now, if this doesn't work or you get an error saying it can't find the model(s) you need to ensure the models are actually loaded and initialised in the current scope.