Tuesday, April 4, 2017

How to Set Global Variable in Laravel (Without Messing up with Migrations)?

I just want to Fetch Title and Tagline of the site from options table of my Database.
I tried Fetching it from AppServiceProvider.php but it shows Error that table does not Exist when I delete all the tables and run PHP artisan migrate.

I also tried Session but Finally, it takes me to the old AppServiceProvider.php method. It works fine but not when we install the Application fresh and run migration!

This is how my AppServiceProvider.php Looks like to get Idea what Exactly I want to do.

public function boot()
{
    $site_options = array();

    $site_title = Options::where('option_name','site_title')->first();
    $site_options['site_title'] = $site_title?$site_title->option_value:'Site Title';

    $site_tagline = Options::where('option_name','site_tagline')->first();
    $site_options['site_tagline'] = $site_tagline?$site_tagline->option_value:'A Simple website!';

    view()->share('site_options',$site_options);
}

I am searching for the answer on Stackoverflow and everywhere but I don't know what to do. I can also Create constructor on all the Controllers and Fetch the Data but then I have to pass the variables with every view and that makes the code look Bad!

Any Standard Solution for this?

PS: Seeding Does not work when I've this code Added into the AppServiceProvider.php not Migration works. I have to Remove this code from AppServiceProvider.php in order to migrate and seed!



via Adarsh Sojitra

Advertisement