prgrm
prgrm

Reputation: 3833

Adding information to a Layout without having to call it on every controller

I have a layout that is used when you are logged in. menu.blade.php.

Then I use it in blade files @extends('admin.layouts.menu')

I want to show some information in the layout, let's say the number of messages near the "message" link in the menu. I could easily do this by adding:

$message_count = Message::where("user_id", Auth::user()->id)->count();

and adding: <div>{{$message_count}}</div> to menu.blade.php

to every single controller and view where the layout is used, but this is clearly not a clean way to do it.

Is there a way to pass information to the view in a single step instead of having to do it in every single controller?

Upvotes: 2

Views: 47

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163758

Use view composers.

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

Register the view composer within a service provider:

public function boot()
{
    View::composer('menu', function ($view) {
        $view->with('messagesCount', auth()->user()->messages->count())
    });
}

Then each time when the menu view will be rendered, it will have $messagesCount variable with counted messages for an authenticated user.

Upvotes: 3

Related Questions