John Davidson

php - Sending variable from Controller to view through route

0 comments
Message:


I want to send data from a logincontroller to routes/web.php.


In my LoginController.php I have


return redirect()
->intended('/dashboard')
->with([
'name'=>'Joe Steel',
'address'=>'Blk 4, Bryton street',
'gender'=>'male',
]);//this is the data I want to send

in my routes/web.php I have


Route::get('/dashboard', function(){
//from session
$names = Session::get('name');//extract name from session
$address = Session::get('address');//extract name from session

return View::make('view/directory/dashboard', [
'name'=>$names,
'address'=>$address]);
//load web view ,
//send name which would be displayed in
//dashboard.blade.php {{$name}} and {{$address}}
});

in my dashboard.blade.php I have


{{$name}} and {{$address}}

This is producing no output. i.e. the location where they where meant to show up in is empty


When I do not give View::make() any variable identifier e.g. View::make('dashboard',[$names,$address])
It produces error
Undefined variable: name (View: /laravel/installed/directory.php)


So I do not know if the route/web.php is receiving anything from the controller and I am also confused on how to pass it to the view through the array.


Please what could be the reason why this is happening


update


I noticed that the session was not being passed from my controller, I do not know what could be the reason for this. Is there something that I am missing?



My Answer:
In order to send data from a controller to a view through the route, you can use the `with()` method when redirecting. Here's an example:

In your LoginController.php:

php
public function login()
{
$data = ['name' => 'John Doe'];

return redirect()->route('dashboard')->with('data', $data);
}


In your routes/web.php:

php
Route::get('/dashboard', function () {
$data = session('data');

return view('dashboard', ['data' => $data]);
})->name('dashboard');


In this example, when the `login()` method in the `LoginController` is called, it redirects to the `dashboard` route and passes the `$data` variable using the `with()` method. In the `dashboard` route, you can access the data using the `session()` helper function and pass it to the view.

Rate this post

4 of 5 based on 1980 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us