Framework: when Sharing Data With All Views using AppServiceProvider migration fails

Created on 29 Sep 2016  路  4Comments  路  Source: laravel/framework

  • Laravel Version: 5.3.10
  • PHP Version: 7
  • Database Driver & Version:

    Description:

Here it's mentioned how to share data with all views:
https://laravel.com/docs/5.3/views#passing-data-to-views
It gives this simple example:

    public function boot()
    {
        View::share('key', 'value');
    }

in my case it ended looking up like this:

    public function boot()
    {
        $setting = Setting::where('name', 'website-title')->first();
        View::share('website_title', $setting);

I then reset my migrations and tried to run them again
php artisan migrate
and I get:

 [Illuminate\Database\QueryException]

  SQLSTATE[42S02]: Base table or view not found: 1146 Table 'images.settings' doesn't exist (SQL: select * from `settings`
 wher
  e `name` = website-title limit 1)

Why is AppServiceProvider running when migration runs? If it must run then what is the best way to share data with all views that will work with migrations?

Steps To Reproduce:

Most helpful comment

@nivincp

sure, like this

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        if(!app()->runningInConsole() ){
            $setting = Cache::rememberForever('website_name', function() {
                return Setting::where('name', 'website_name')->first();
            });

            $pages = Cache::rememberForever('pages', function() {
                return Page::active()->get();
            });
            View::share('pages', $pages);
        }
    }

this is the key:

!app()->runningInConsole()

All 4 comments

@nikocraft The above link is dead. Just wondering how did you solve the issue?

@nivincp

sure, like this

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        if(!app()->runningInConsole() ){
            $setting = Cache::rememberForever('website_name', function() {
                return Setting::where('name', 'website_name')->first();
            });

            $pages = Cache::rememberForever('pages', function() {
                return Page::active()->get();
            });
            View::share('pages', $pages);
        }
    }

this is the key:

!app()->runningInConsole()

@nikocraft

That's a very nice solution. Thanks mate!

Was this page helpful?
0 / 5 - 0 ratings