【问题标题】:How Can I Pass Variable related to Auth in multiple laravel controller?如何在多个 laravel 控制器中传递与 Auth 相关的变量?
【发布时间】:2019-08-01 14:00:06
【问题描述】:

我的 laravel 控制器中有多种方法,如下所示:

public function daily(){
    $sites = Site::all()->where('owner_id', '==', Auth::user()->owner_id);
        return view('backend.daily',compact('sites'));
}
public function weekly(){
    $sites = Site::all()->where('owner_id', '==', Auth::user()->owner_id);
        return view('backend.weekly',compact('sites'));
}
public function yearly(){
    $sites = Site::all()->where('owner_id', '==', Auth::user()->owner_id);
        return view('backend.yearly',compact('sites'));
}
...

我在控制器构造器中使用了它:

public function __construct() {
        $sites = Site::all()->where('owner_id', '==', Auth::user()->owner_id);
        View::share('sites', $sites);
}

并在 AppserviceProvider 的 boot() 方法中使用,但这不起作用并出现以下错误:

"Trying to get property 'owner_id' of non-object"

正常使用时没有错误!

在每种方法中,我都使用了一个名为 $sites 的变量,但它在多个视图中使用,我想使用 $sites 一次,并且我的代码希望像这样更短:

public function daily(){
        return view('backend.daily',compact('sites'));
}
public function weekly(){
        return view('backend.weekly',compact('sites'));
}
public function yearly(){
        return view('backend.yearly',compact('sites'));
}
...

我怎样才能做到这一点?

【问题讨论】:

    标签: laravel variables methods controller multiple-views


    【解决方案1】:

    试试这个:

    optional(Auth::user())->owner_id
    

    如果用户未登录,您可能无法从数据库中获取网站。

    【讨论】:

    • 先生,我的授权没有问题,我应该在where('owner_id', '==', Auth::user()->owner_id不能忽略的地方使用它
    • 所以这应该可以工作:where('owner_id', '==', optional(Auth::user())->owner_id)。你试过了吗?
    • 是的,这有效,但没有显示记录!看起来当我在刀片上 dd($sites) 时未定义站点变量
    • 确保你最后使用了->get()where()。喜欢Site::where('owner_id', '==', Auth::user()->owner_id)->get();。在AppServiceProvider 中尝试dd($sites) 以确保它包含数据。
    • 我在 AppServiceProveder 和 Constructor 的 boot() 方法中使用了这段代码,但它什么也没显示,当我使用 dd($sites) 时,它显示空集合Collection {#147 ▼ #items: [] },而我的数据正常模式!
    猜你喜欢
    • 2019-09-10
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 2018-04-24
    • 2019-08-28
    • 1970-01-01
    • 2019-11-11
    • 1970-01-01
    相关资源
    最近更新 更多