Universal Link
Universal Link

Reputation: 307

Laravel | Running Query For Multiple Views Without Duplicating Code

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

Answers (2)

Imran
Imran

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

Ivan Alvarado
Ivan Alvarado

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:

  • My page load only the neccesary including the data of the view
  • After load, with Jquery (in my case), I get the last notifications in a simple component via ajax, so, if the user want to see more notifications, he can do it by two ways, first, clicking in the "Load more" button, or, clicking in "See all notifications", then, I send him to one view with all notification's user.

In this way, you only need load script at the end of your layour, and always gonna work.

Upvotes: 0

Related Questions