Reputation: 307
I'm building an application that queries the same set of commands to the database for almost every view. For example, notifications
; I need to query to get all of the notifications for the user for every view where the user is logged in. In the controllers I'm doing this:
public function index() {
$notifications = Notification::whereUserId(Auth::user()->id)->get();
return view('home', compact('notifications'));
}
This is fine for 1 view, but I'm retrieving this in every index function call, for every view. Is there a better way of doing this without duplicating code?
Like retrieving the notifications in 1 file only.
Thanks.
Upvotes: 1
Views: 229
Reputation: 4750
In the boot()
method of App\Providers\AppServiceProvider
add the following line:
if(auth()->check()){
View::share('notifications', Notification::whereUserId(auth()->id())->get());
}
This way the notifications
variable will be shared in all of your views(.blade files).
Instead, if you want to just share data in some specific views then you can use view composer. Check the documentation here: https://laravel.com/docs/5.8/views#view-composers
Upvotes: 5
Reputation: 21
Why do you do it in the front? .... I have a similar situation, I have a simple app, implementing traditional page by page behavior, I do this:
In this way, you only need load script at the end of your layour, and always gonna work.
Upvotes: 0