I am working in laravel 5.4 project and want to set and get session value with laravel view show.blade.php file.Is there any way to achieve this.
1 Answer
You should not set the session value in blade file. It's a bad approach (take it to controller)
but if you still want to do it
{{ session()->put('my_test_key','my_value')}}
and you can get it by
{{ session()->get('my_test_key') }}
If you take a look into how view is rendered in php/laravel it would make sense not to put something in session using view.
Inside controller when view is rendered:
return view('show.blade.php',compact('my_var'));
at this stage your value will be put to session before returning the compiled view
if we put value to session using controller not the view it will look like:
session()->put('my_test_key','my_value') // value is put to session before compiling the view
return view('show.blade.php',compact('my_value'));
Calculations are the responsibility of Controller not View and at first glance at your controller anyone and tell you are putting some value to Session.
On the other hand if we are putting something in session using View if someone want to debug your code they have to dig through the view to find that line. Believe me its not easy to dig through views and after a month also you wouldn't be able to find that line in View.