【问题标题】:passing multiple data from controller to all views by view composer通过视图编辑器将多个数据从控制器传递到所有视图
【发布时间】:2020-03-27 07:14:22
【问题描述】:

我的控制器:

<?php
public function Dashboard()
{
    foreach ($roles as $item) {

        if (Auth::User()->hasRole("$item->name")) {
            $office_role = $item->name;
        }
    }
    $office_id = Auth::User()->office_id;


    $return_counter = Notification::where('recipient_office_id', $office_id)->where('recipient_office_role', $office_role)->where('status', 0)->where('type', 'Return')->count();

    $return_counter_pending = Notification::where('recipient_office_id', $office_id)->where('recipient_office_role', $office_role)->where('status', 2)->where('type', 'Return')->count();
    return view('Dashboard', compact('return_counter', 'return_counter_pending'));
}

我想通过视图编辑器将这些数据传递给所有视图。但是如何实现这一点,我尝试过,但是每当我尝试使用身份验证时,我都在引导方法中无法访问登录页面。

【问题讨论】:

    标签: laravel


    【解决方案1】:

    您可以使用刀片模板将这些数据从控制器传递到视图,您可以从这里查看如何使用刀片模板。 https://laravel.com/docs/5.4/blade

    【讨论】:

    • 不,我必须将数据传递给主刀片...所以我必须使用视图编辑器或服务提供商
    • 主刀片是您视图的布局刀片吗?
    • 要显示 Auth 用户数据,您需要使用 if(Auth::guest) 验证用户是否已经登录
    【解决方案2】:

    您可以在 AppServiceProvider 中使用此代码

      View::composer('*', function($view) {
        if(Auth::check()) {
          $view->with('foo', 'bar');
        }
      });
    

    或者创建一个新的 View Composer https://laravel.com/docs/7.x/views#view-composers

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-23
      • 2013-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多