如何将相同的数据传递给laravel中的多个视图

hab*_*bib 3 php laravel laravel-5 laravel-5.2

从控制器方法,我发送$notifications到主页视图并在我网站的标题上显示通知。

个人资料视图扩展了主页视图,我还想在个人资料视图上显示通知。

但是当我请求配置文件视图时,它会生成未定义变量 $notifications 的错误。

我认为一种解决方案是$notifications在从控制器方法返回配置文件视图时发送,但在网站中,我想在很多视图上显示通知选项卡,所以这是我正在思考的正确方式。

我通过以下方式返回了主页视图

return view('home')->with(['unseen_notification_counter'=>$unseen_notification_counter,'notifications'=>$notifications]);
Run Code Online (Sandbox Code Playgroud)

这是标题部分的主页视图中的代码

<ul class="dropdown-menu" id="notificationlist">
    @foreach($notifications as $notification)
        <li>
            <a href="{{route('user.profile',$notification->id)}}" class="dropdown-item">
                <img src="http://localhost/webproject/public/user_images/{{$notification->image}}" class="img-thumbnil" width="20px" height="20px">
                <strong>{{$notification->username}}</strong>
                <span style="white-space: initial;">sent you a friend request.</span>
            </a>
        </li>
    @endforeach
</ul>
Run Code Online (Sandbox Code Playgroud)

Rwd*_*Rwd 5

如果您想将相同的数据传递给应用程序中的多个视图,您可以使用View Composers

例如,在boot()您的 AppServiceProvider 方法中,您将有类似的内容:

public function boot()
{
    view()->composer(['home', 'profile'], function ($view) {

        $notifications = \App\Notification::all(); //Change this to the code you would use to get the notifications

        $view->with('notifications', $notifications);
    });
}
Run Code Online (Sandbox Code Playgroud)

然后,您只需将不同的刀片文件名(就像使用路由一样)添加到数组中。


或者,您可以与所有视图共享通知:

public function boot()
{
    $notifications = \App\Notification::all(); //Change this to the code you would use to get the notifications

    view()->share('notifications', $notifications);
}
Run Code Online (Sandbox Code Playgroud)