laravel share variable across all methods in a controller
Solution 1
I solved the problem by using Laravel's view composer. I made a header.blade.php and passed the $pages variable to it and added following code to my routes.php file.
View::composer('header', function($view){
$pages = Page::all();
$view->with('pages', $pages);
});
Solution 2
I think a fairly straightforward way to do this is by using the controller's constructor. It's sometimes helpful to be able to see the vars available to all methods in a controller from within that controller, instead of hidden away in a service provider somewhere.
class MyController extends BaseController
{
public function __construct()
{
view()->share('sharedVar', 'some value');
}
public function myTestAction()
{
view('view.name.here');
}
}
And in the view:
<p>{{ $sharedVar }}</p>
Solution 3
You can use singleton like the following
App::singleton('data', function() { return array('abc' => 1); });
This way, you can call it anywhere in your controller or template like
$data = App::make('data');
Following this, you could try using a bundle developed by Phil here, https://github.com/Phil-F/Setting. Once installed, then you can just refer it in controller or template by
Setting::get('title')
Of course, you can set it anywhere by using
Setting::set('title', 'Portfolio');
Setting allows you store them both in cache and json file which might be another way to get the value back.
imran
Updated on June 05, 2022Comments
-
imran almost 2 years
i am making a simple website in PHP laravel framework where the top navigation links are being generated dynamically from the database. I am generating the $pages variable in the home controller action and passing to layout file. My code is as below:
public function home() { $pages = Page::all(); return View::make('home')->with('pages', $pages); } public function login() { return View::make('login'); }
But when i try to access the login action, i get the error variable $pages not found since the $pages variable is being accessed in layout file. How can i share the same variable across all the actions in a controller?
-
Lucky Soni over 9 yearsyou are mixing JavaScript and PHP