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) }}
Related
I have a bit of a complicated issue. I could use some help.
I have a form that is being handled by the following function:
$module = request('module');
$classe = request('classe');
$horaire = request('horaire');
$date = request('date');
$students = DB::select('SELECT * FROM `etudiants` WHERE etudiants.id_classe = '.$classe);
return view('g_absence.absence',['module'=> $module, 'classe'=>$classe,'horaire'=>$horaire,'date'=>$date,'students'=>$students]);
I take the values $module, $class, $horaire, $date and $students and need to use them inside a different view: g_absence.absence. This works fine and when the view is returned I have access to said variables.
The issue is, inside the g_absence.absence view, I have another form that also needs to be handled, and because the url remains the same even tho a different view is returned, I cant make two posts for the same path.
web.php:
Route::get('/testboy', [App\Http\Controllers\g_absence::class,'index'])->name('marquer');
Route::post('/testboy',[App\Http\Controllers\g_absence::class, 'marquer']);
Route::post('/testboy',[App\Http\Controllers\g_absence::class, 'ajoutabsence']);
The first line is the one that send to the form page just a simple
return view
The second one handle the form in that view
The third one, I want it to handle the form inside the
g_absence.absence view, but they share the same path.
Excuse me if I'm being unclear, I'm a bit of a beginner in Laravel
your problem is using the same route for different methods
basically the first route gets executed every time you use the '/testboy' action that is why your second function never get's called.
you can solve this issue by changing your urls for example:
Route::post('/testboy-marquer',[App\Http\Controllers\g_absence::class, 'marquer']);
Route::post('/testboy-ajoutabsence',[App\Http\Controllers\g_absence::class, 'ajoutabsence']);
Or you can use one function that's handle both with one url by pathing additional parameter to your url depending on your function call :
Route::post('/testboy?type=marquer',[App\Http\Controllers\g_absence::class, 'ajoutabsence']);
in your function check the type :
if(request('type') == 'marquer') {
execute marquer logic here...
} else {
execute absence logic here...
}
Using method and path with two functionalities is wrong, but if you want to somehow use both routes my same method and path which I don't recommend you must let the request to pass through like a middleware in your first block of code Instead of return a view.
Recommended way is to have 2 routes with different paths or at least one route with a parameter by which you can determine what code block must be executed.
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.
Right now, if I have a parameter in a URL in one of my Laravel projects, I have to detect the route and grab the parameter:
Route::get('mission/{name}', 'MissionsController#show');
Pass the $name parameter as an argument to my controller:
class MissionsController extends BaseController {
public function show($missionName) {
...
}
}
Then pass it along to the view that is returned in my controller method:
return View::make('missions.mission', array(
'name' => $missionName
));
Before then using the $missionName variable in my view:
<p>{{ $missionName }}</p>
This is quite a roundabout way of doing so. Is there any way I can get the parameter from the URL directly in my view? I've tried accessing the $_GET superglobal, but it is empty. Surely there must be a better way of doing this.
Thoughts?
Use this code :
{{ Route::current()->getParameter('theParameterName') }}
EDIT: Above doesn't seem to be supported anymore in recent Laravel versions. You should use #lukasgeiter answer instead:
Route::input('name');
There is a nice shortcut for Route::current()->getParameter():
Route::input('name');
For small projects or simple examples, it may seem like this is a "roundabout" way, however this is the way it should be. In order to create more reusable, quality code, you need to have this separation of concerns. An over-simplified idea follows.
It is your route's job to figure out which controller needs to be called, and to make sure it is called with the correct parameters.
It is your controller's job to read the state of the application (input), communicate with the model (if needed), send the data into the view, and return the response. There's plenty opinion on whether or not this violates the Single Responsibility Principle, but no need to go into that here.
It is the view's job to use the data passed to it to build the response. The view shouldn't care where the data came from or how it was gotten, only that it now has it and can do what it needs. Your $missionName should be able to come from a URL segment, a URL request variable, a field on a model, or any other place you can think of, but the view shouldn't know any of that.
I am trying to make commenting on my site modular, so I have attempted to use view::composer to run the queries that are required to populate the comment data whenever the comment view is called, then my plan was to include the comment view in any place i needed comments, and then connect it to the appropriate comment table in my database.
The functions I have made for commenting fit each of the comment tables I've created and I've made the view composer work, the only thing is now since the function to get all the comment data is being called by the view composer when the comment view is being set up, that function no longer has access to the id that was being passed to it ( normally it is in the route like: Route::get('/{id}', 'controller#method');).
I have been searching for hours trying to figure out how to pass the variable in, but with no luck.. Maybe I'm missing some really basic detail, Idk, but I can't figure it out and haven't found anything that solves the problem, please help..
It seems like it should be so simple, I've tried doing:
$var = Route::get('/{id}', function($id){ return $id; }
Which i thought might do it, but the result was an error saying whatever the response was couldn't be converted to string.
Option 1: Access the route parameter
View::composer('comment-view', function($view){
$id = Route::current()->getParameter('id');
});
Option 2: Use the view to access the id
In your controller: return View::make('view-name')->with('commentId', $id);
View::composer('comment-view', function($view){
$id = $view->commentId;
});
I have a resource controller for member data. All of the usual resource functions, including edit, are working perfectly. I am trying to add additional edit functions within this controller so that I can create views that only are for specific subsets of the Member model data, since the data set is rather large. So, I've set up the extra routes and functions. But when I attempt to link to the edit2 resource, Laravel will not create the proper link. I don't know what I'm doing wrong. Code:
Route:
Route::get('members.edit2', array('as'=>'edit2', 'uses'=> 'MembersController#edit2'));
Route::resource('members','MembersController');
MembersController:
// Regular edit function -- works just fine:
public function edit($id)
{
$member = $this->member->find($id);
return View::make('members.edit', array(
'member'=>$member, ...
));
}
// Extra edit2 function -- should work if I could successfully route to it:
public function edit2($id)
{
$member = $this->member->find($id);
return View::make('members.edit2', array(
'member'=>$member, ...
));
}
show.blade.php:
// normal edit link (works fine, see source code below):
edit
// additional edit2 link (creates a bad link, see source code below):
edit
source code:
// normal link that uses edit for member id=27:
edit
// link that attempts to use edit2 for same member:
edit
I'm sure there is a way of doing this. It doesn't matter whether I use the named route 'edit2' rather than 'members.edit2', the exact same bad link is created. I've tried every combination I can think of. Laravel docs are not at all helpful for this. Thanks!
Your don't declare your edit2 route as you should do. Your first mistake is that the member's id you want to edit is not passed as a parameter and the second one that by calling this {{route('edit2')}} Laravel expects a url like /members.edit2 which is never going to appear. You should better use sth like /members/{id}/edit2.
Try using this:
Route::get('members/{id}/edit2', array('as'=>'edit2', 'uses'=> 'MembersController#edit2'));
and call it like:
{{ route('edit2', [$id]) }}
Also be careful, whenever you call Url::route() or simply route() you should pass their parameters in an array like:
{{route('myRoute', ['par1', 'par2', 'par3', ...]}}