Passing a variable between two controllers using session
Hello Laracasts community, I have got two controllers(ProductsCobttroller and FrontController) in my Laravel 5.4 project, The ProductsController is a CRUD and am using the show function to fetch image name from products table and store in a variable. Now I want to pass the variable to a view called front.blade.php which is controlled by FrontController. Am try to use sessions to achieve the task but I keep getting errors. Please assist?
ProductsController
public function show($id)
{
$items = Category::find(6)->products()->where('image' , true)->get();
Session::put('item', $items);
}
FrontController
public function index(){
Session::get('item');
return view('front.index' , compact('item'));
}
Routes
Route::group(['middleware' => 'web'], function () {
Route::get('/' , 'FrontController@index')->name('front.index');
});
Front.blade.php
@foreach($item as $items)
<img src="{{ asset('images/'.$items->image) }}">
@endforeach
public function index(){
$item = Session::get('item');
return view('front.index' , compact('item'));
}
(I'm not 100% sure why you're using the session to do this, I'm assuming you are doing something more complicated than this but you've vastly simplified the example)
Ok Jack, I am trying to pass the variable from the ProductsController to the FrontController so that I can use it in fron.blade view. Am not sure if that is the way to use Session to pass variables between controllers...?
@tykus Now thats the bone of contention, I am tying to get elements of a particular id from the database and I opted to use the productsController then pass the variable to the frontController. How can I use the frontcontroller@index to get the products of a particular id? ..Regards
Just a quick recap of my project: I am creating an e-commerce project whereby I have added images to a database and have used one to many relationship to sort them(many categories have one product), Every function in the ProductsController(a CRUD) works fine. Now I want to fetch images of a particular category and display to a view called Front.blade.php.... How can I go about achieving that using the frontController ?