Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel service provider to retrieve data from database

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.

like image 960
mana Avatar asked Apr 10 '19 06:04

mana


People also ask

How can we get data from database in controller in Laravel?

After configuring the database, we can retrieve the records using the DB facade with select method. The syntax of select method is as shown in the following table. Run a select statement against the database.

What does service provider do in Laravel?

Service providers are the central place to configure your application. If you open the config/app.php file included with Laravel, you will see a providers array. These are all of the service provider classes that will be loaded for your application.

What is route service provider in Laravel?

All Laravel routes are defined in your route files, which are located in the routes directory. These files are automatically loaded by your application's App\Providers\RouteServiceProvider . The routes/web.php file defines routes that are for your web interface.


1 Answers

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');
});
like image 141
ajthinking Avatar answered Sep 16 '22 13:09

ajthinking