Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How put data in app.blade.php from controller in Laravel 5

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

like image 857
Jensej Avatar asked Mar 07 '15 14:03

Jensej


Video Answer


2 Answers

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>
like image 30
mili Avatar answered Oct 04 '22 02:10

mili


To inject data into a layout view (a view that's @extended 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'
]
like image 198
lukasgeiter Avatar answered Oct 04 '22 02:10

lukasgeiter