samedi 25 février 2017

Sharing a global variable from database result to the view?

In my header and in the footer are some dynamic navigations from the database. So i need a result from the database on each site in Laravel.

In Laravel's documentation under Sharing Data With All Views is the way descripted.

So i created the Query in the AppServiceProvider under boot():

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $navigation = \App\Navigation::all();
        view()->share('navigation', $navigation);
    }

    // ...
}

It works, but i work with CI and everytime the tests are failing

> Illuminate\Foundation\ComposerScripts::postInstall
> [ -f /usr/bin/php71 ] && /usr/bin/php71 artisan optimize || php artisan optimize

[Illuminate\Database\QueryException]                                         
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'homestead.navigation' doesn't exist (SQL: select * from `navigation`)                                                                       

[Doctrine\DBAL\Driver\PDOException]                                          
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'homestead.navigation' doesn't exist                                                      

[PDOException]                                                               
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'homestead.navigation' doesn't exist

It's because the tables are not migrated at this time...

So i catch the Exception like this:

try {
    $navigation = \App\Navigation::all();
} catch (\Illuminate\Database\QueryException $e) {
    $navigation = [];
}
view()->share('navigation', $navigation);

Is this the right way or is there a better way to share a database result to the view?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2mhpsVo
via IFTTT

Aucun commentaire:

Enregistrer un commentaire