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?
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With