How to share data with all views in Laravel 5.3 the right way

How do you share data to all views in Laravel 5.3? Well if you look at the documentation it gives this simple example

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        View::share('key', 'value');
    }

This example won't work right away, it will give you an error complainig about Class 'App\Providers\View' not found  You'll have to import it first like so

use View;

Now let's take it step further and get some data from database.

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

To access it in your view you do this

{{$website_title->body}}

All is working well, but what happens if you reset your migrations and run them again using php artisan migrate In my case when I run that command I got an error like this

[Illuminate\Database\QueryException]

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

It complained that the table settings does not exists. Ofcourse it does not exists, I just rolled back the migration. So what is going on here? Why is Laravel looking for settings table when running migrations. It turns out Laravel will run AppServiceProvider boot method when running migrations. So how do you run your migrations and also share data to all views in your applications. Well it turns out you have to do it like this

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

You have to check if your application is running in console by calling runningInConsole() method. If you run your migrations now, they should work and also your views will get the data they need.