Faisal Mehmood Awan
Faisal Mehmood Awan

Reputation: 436

Laravel 5.3 make a query to database and pass it all views

I have a some dynamic data that I want to fetch from database and pass it to all views. I tried to make some examples from internet but they seems to be not working in my situation like

public function boot(){}

to which I can't make a database query only pass hardcoded values. Another method I have tried is a base controller but the view gives me error when accessing the variable

$query = DB::table('users')->first();
\View::share('user', $query);

Anyone have a BaseController based solution will be appreciated and if I missed something please do remind me

Upvotes: 3

Views: 2556

Answers (3)

Herry Gallery
Herry Gallery

Reputation: 1

It is working from boot :

View::share ('variabelname', DB table first () etc etc)

However i encounter a problem :

If i delete tables or drop tables, then run migration and seed, I got error :

base tabel / view not found.

So i have to comment out that line from App Service Provider before any migrate refresh etc.

Upvotes: 0

apokryfos
apokryfos

Reputation: 40653

According to the docs at https://laravel.com/docs/5.4/views#sharing-data-with-all-views:

Occasionally, you may need to share a piece of data with all views that are rendered by your application. You may do so using the view facade's share method. Typically, you should place calls to share within a service provider's boot method.

Again as an example in that site you should add this to one of your service providers:

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        if (!app()->runningInConsole()) {
            $query = DB::table('users')->first();
            \View::share('user', $query);
        }
    }
}

Upvotes: 7

shafiq.rst
shafiq.rst

Reputation: 1296

You can use view composer. "View composers are callbacks or class methods that are called when a view is rendered. If you have data that you want to be bound to a view each time that view is rendered, a view composer can help you organize that logic into a single location."

you can find more detail on https://laravel.com/docs/5.3/views#view-composers

Upvotes: 0

Related Questions