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.
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.
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');
});
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 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.
boot
. Then use that data to build your config before finally publishing it. All in the boot method. – Paragon