dongrang9300 2015-03-18 22:49
浏览 32
已采纳

如何传递多个到多个关系来查看数组[Laravel 5]

I try to pass array to view for my relations.... I have users and projects table in realation....

Here is User Model:

public function projects(){
    return $this ->belongsToMany('App\Project','project_user');
}


public function getUserList(){
    return $this -> projects;
}

Here is my home controller:

public function project(User $project){
            $this -> selected = $project;
            return view('projects',array('selected' =>$project -> selected -> getUserList()->lists('id') ));
        }

NOTE

If I change my home controller, this line:

return view('projects',array('selected' => $project -> selected -> getUserList()->lists('id') ));

into this:

return view('projects',array('selected' => Auth::user -> getUserList()->lists('id') ));

it works fine...

Anyone know why It now work with method injection?

  • 写回答

1条回答 默认 最新

  • dowaw80220 2015-03-19 00:07
    关注

    Short answer: Laravel doesn't know what to do when you type-hint your User model.

    Longer answer: Since the current logged in user's information is stored in the Authentication portion of Laravel's code, one option is to type-hint the Illuminate\Contracts\Auth\Guard interface (API docs) in your method descriptor to get an instance of it.

    You can then use the user property to access an instance of the User model reflecting the currently logged in user. This code is essentially what you already have here: Auth::user -> getUserList()->lists('id').

    The benefit to using the Guard interface inside of Illuminate\Contracts is that if a package or service provider redefines the concrete implementation of the Guard interface (the reason to do this would be swapping out how authentication works in your application), your code will not require changes due to it being bound to the contract defined by that interface, rather than using the Auth facade which may no longer function in the same manner.

    Hope this helps! Feel free to ask questions :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大