将信息添加到 Layout 而无需在每个控制器上调用它

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

我有一个布局,在您登录时使用。menu.blade.php

然后我在 blade 个文件中使用它 @extends('admin.layouts.menu')

我想在布局中显示一些信息,比如菜单中 "message" link 附近的消息数。我可以通过添加来轻松做到这一点:

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

并添加:<div>{{$message_count}}</div>menu.blade.php

每个单独的控制器和使用布局的视图,但这显然不是一个干净的方法。

有没有一种方法可以一步将信息传递给视图,而不必在每个控制器中都这样做?

使用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

在服务提供商中注册视图编辑器:

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

然后每次呈现 menu 视图时,它都会有 $messagesCount 变量,其中包含经过身份验证的用户的计数消息。