passing variable through controller method attatched to view::composer in Laravel - php

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

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

Laravel : form does not change the URL after submit, causing me to be unable to do another POST in web.php

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.

Laravel redirect to view with specific URL parameters (gives route not defined)

This is my first Laravel project, i'm making a routing mistake and have been trying to solve it for days now, solution must be very simple, so i'm missing something. I attempted some similar solutions I found in other posts here, but they contained much more complex code and only made things worse for me at this point.
I have a GET route like:
Route::get('peppers/{id}', function ($id) {
//return $id;
$pepper = DB::table('peppers')->get();
return view('peppers',['id' => $id,'pepper'=>$pepper]);
})->name('peppers');
And I also have a simple POST route. (for a form that I used on another page)
It inserts everything correctly into my database. The problems is in the redirect.
Route::post('pepperCreate', function (\Illuminate\Http\Request $request) {
$post = $_POST;
$pepperType = $_POST["pepperType"];
$pepperURL = $_POST["pepperURL"];
$pepperAuthor = $_POST["pepperAuthor"];
and so on... ending with:
return redirect()->route('peppers/{id}', [$id]);
})->name('pepperCreate');
But every time i try to redirect, it gives me an error saying:
Route [peppers/{id}] not defined.
(My question is: Did i not just define that GET route, because it works when I click into that URL) with:
{{$topic->topicTitle}}
After days of trying different variations of this, i'm trying to figure out what i'm missing here. Any input is appreciated.
Indeed, because you need to use your route's name, and use an associative array for the parameters too, as in:
return redirect()->route('peppers', ['id' => $id]);
Hope this helps!

How to access values of multiple parameters passed to Laravel controller

I am trying to figure out how to access two (or more) parameters passed to a Laravel controller. I know how to create the route, and the URL is created correctly, but then I can only access the first passed parameter in my controller.
Route:
Route::get('managers/{id}/{parameter2}', array('as'=>'dosomething', 'uses'=> 'ManagersController#dosomething'));
where the first parameter is obviously the $id for managers, and the second parameters is to be processed by the controller.
View:
Do Something
generates the URL:
http://domain/managers/1/2
where 1 is easily accessed as the $id for managers, but when I try to access the 2nd parameter "2" using $parameter2, e.g. using a simple return: "id=$id and parameter2=$parameter2" statement, I get an "unidentified variable: $parameter2" error.
What am I doing wrong?
Is there a better way to pass multiple parameters? I'm especially asking the "better way?" question because what I want to do is use the 2nd parameter to change a value in a database table, and using a 'get' method, somebody could change the parameter value in the URL and therefore cause mischief. Must I use a 'post' method? I'd love to be able to use a link, since that works much better with the design of my application.
Thanks!
I was asked to include the controller, which I'm happy to do. Initially, just for testing, as I mentioned, my controller was a simple return to display the values of the two passed parameters. But here is what I want to be able to do, including the actual name of the function ("update_group" rather than "dosomething") --
ManagersController:
public function update_group($id)
{
DB::table('groups')->where('id','=',$parameter2)->update(array('manager_id'=>$id));
return Redirect::route('managers.show', array('id'=>$id));
}
The update table works perfectly if I replace $parameter2 with an actual value, so that syntax is fine. The issue is that Laravel says that $parameter2 is an undefined variable, despite the fact that the URL contains the value of $parameter2 as you can see above.
And since it occurs to me that the answer to this may involve adding a function to the Manager model, here is the current
Manager.php
class Manager extends Eloquent {
protected $table = 'managers'; ... (mutator and error functions)
}
Just change
public function update_group($id)
to
public function update_group($id, $parameter2)
All looks ok in your route. Seeing the controller code would help, but likely, you may not have a second parameter in your controller's dosomething() method.
public function dosomething($id, $parameter2){
var_dump($id).'<br />';
var_dump($paremter2);
}
If that isn't the case, you can try dumping it from the route's callback to further diagnose.
Route::get('managers/{id}/{parameter2}', function($id, $parameter2)
{
var_dump($id).'<br />';
var_dump($paremter2);
});
Depending on your use case, you can pass them in a query string like so: but it isn't really the 'best way', unless you're doing something like building an API that won't use the same variables in the same order all the time.
/managers?id=1&paramter2=secondParameter
var_dump(Request::query('id')).'<br />';
var_dump(Request::query('paramter2'));

Unable to route to second edit resource Laravel-4

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', ...]}}

Categories