Laravel service provider to retrieve data from database
Asked Answered
A

1

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.

Appliance answered 10/4, 2019 at 6:31 Comment(2)
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.Paragon
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?Appliance
P
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');
});
Paragon answered 10/4, 2019 at 7:8 Comment(4)
Is this going to do this for every request?Disinterested
@Disinterested yesParagon
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.Desdemona
due to php artisan package:discover which may happen in deployment before having actual connection to database, if you wish to access db data in service provider, consider using try catch the error.Finagle

© 2022 - 2024 — McMap. All rights reserved.