I Need to put some dynamic data from controller to app.blade.php, but I can't find any controller. Where I sholud do this? Thanks
Thanks to lukasgeiter's answer. But it needs some modifications to get it working with all the views rendered by Laravel.
You need to put '*' character as a wildcard, so you may attach a composer to all views
View::composer('*', function($view){
//any code to set $val variable
$val = 'bar';
$view->with('foo', $val);
});
so complete class of app\Providers\ComposerServiceProvider.php
will be like,
<?php
namespace App\Providers;
use View;
use Illuminate\Support\ServiceProvider;
class ComposerServiceProvider extends ServiceProvider {
public function boot()
{
View::composer('*', function($view){
//any code to set $val variable
$val = 'bar';
$view->with('foo', $val);
});
}
public function register()
{
//
}
}
Also register service provider in config\app.php
file as,
'providers' => [
// Other Service Providers...
App\Providers\ComposerServiceProvider::class,
],
Now you can use $foo
variable in your resources\views\layouts\app.blade.php
file as
<div>
{{$foo}}
</div>
this will render to client as
<div>
bar
</div>
To inject data into a layout view (a view that's @extend
ed by others) you can use a view composer. How you do that is actually pretty well explained in the documentation
Create a service provider (inside app/Providers
):
<?php namespace App\Providers;
use View;
use Illuminate\Support\ServiceProvider;
class ComposerServiceProvider extends ServiceProvider {
public function boot()
{
//
}
public function register()
{
//
}
}
Now inside the boot()
method you register your view composer:
View::composer('app', function($view){
$view->with('foo', 'bar');
});
After that, don't forget to register the service provider in config/app.php
by adding it to the providers
array:
'providers' => [
// other providers
'App\Providers\ComposerServiceProvider'
]
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