6

I'm new to Laravel service provider, All I want is to pull the database data out and return it, so my config file can access to that data.

How can I do this in Laravel service provider.

mana
  • 1,075
  • 1
  • 24
  • 43
  • Can you explain what you mean with "so my config file can access that data"? Are you doing a package? If so can you try putting the database queries in your packages serviceprovider method `boot`. Then use that data to build your config before finally publishing it. All in the boot method. – ajthinking Apr 10 '19 at 06:52
  • I'm creating a custom service provider. Ok I'll add the query in the boot() method. How can I access to that data from other location in my application? – mana Apr 10 '19 at 06:57

1 Answers1

7

Example using the boot method to access database and publish it to a temporary config key.

class YourServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $welcomeMessage = "Welcome " . \App\User::first()->name;
        config(['your-namespace.message' => $welcomeMessage ]);
    }

Later in other files across your application you can access it like this

Route::get('/', function () {
    return config('your-namespace.message');
});
ajthinking
  • 3,386
  • 8
  • 45
  • 75
  • Is this going to do this for every request? – bandejapaisa Jul 25 '20 at 15:45
  • @bandejapaisa yes – ajthinking Jul 26 '20 at 10:12
  • 5
    But it's not recommended. When you first clone and run `composer install` without having actual connection to database yet, it will return an error when laravel trying to discover new packages. Depends on where you're going to use those configs, if it's within Controller probably using a Middleware would be the better option. – adods Apr 16 '21 at 06:50