Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel share variable across all methods in a controller

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?

like image 975
imran Avatar asked Sep 01 '25 22:09

imran


2 Answers

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>
like image 130
omarjebari Avatar answered Sep 03 '25 12:09

omarjebari


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.

like image 33
windmaomao Avatar answered Sep 03 '25 13:09

windmaomao