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?
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 :)