Reputation: 45
I am trying to pass a variable to my basic layout. This is because I need it in all pages. I thought that writing something like that on my BaseController
protected function setupLayout()
{
if ( ! is_null($this->layout))
{
$footertext = MyText::where('status', 1);
$this->layout = View::make($this->layout, ['footertext' =>$footertext ]);
}
}
}
And on my I thought that writing something like that on my main.blade.php could work.
{{ $footertext }}.
Instead I having this error,
Undefined variable: footertext
and after two hours of looking around...I didn't find any solution. Any help is welcome.
Upvotes: 4
Views: 9413
Reputation: 521
In Laravel 5.6 none of these methods work.
AppServiceProvider
:
public function boot()
{
View::share('key', 'value');
}
Where View
is the facade Illuminate\Support\Facades\View
Upvotes: 1
Reputation: 393
For laravel 5.3 I am using in AppServiceProvider.php
inside app/Providers
public function boot()
{
view()->composer('layouts.master', function($view)
{
$view->with('variable', 'myvariable');
});
}
*Dedicated Class inlcuded
Upvotes: 1
Reputation: 160
Not long ago I was trying to do the same.
If you are using Laravel 5 you can edit the AppServiceProvider.php inside app/Providers
and register a provider for this layout like:
public function boot()
{
view()->composer('my.layout', function($view) {
$myvar = 'test';
$view->with('data', array('myvar' => $myvar));
});
}
Now if you are using Laravel 4 I think it's more simple. In the app/filters.php
:
View::composer('my.layout', function ($view) {
$view->with('variable', $variable);
});
In both ways any variable you pass will be available to all templates that are extending the master template.
References:
https://laracasts.com/discuss/channels/general-discussion/laravel-5-pass-variables-to-master-template https://coderwall.com/p/kqxdug/share-a-variable-across-views-in-laravel?p=1&q=author%3Aeuantor
Upvotes: 5
Reputation: 67505
Sometimes we need to pass data from controller to view in laravel like working with database query, select option and more. it’s simple and easy with built in function in laravel. We can send data from controller to view easily with with() in laravel. Also there are more way to send or pass data to view from controller. I am describing some easy way how to pass data form controller to view in laravel.
1. Passing an array :
$data = array(
'name' => 'Rakesh',
'email' => '[email protected]'
);
return View::make('user')->with($data);
//Accesing $data on view :-
{{$data}}
{{$data['email']}}
2. Working with query :
function view() {
$q = Model::where('name', '=', 'Foo')->first();
$users = Model::order_by('list_order', 'ASC')->get();
return $view->with('users', $users)->with('q', $q);
}
//Accesing on view :-
{{ $q->name }}
Hope that help you :)
Upvotes: 0