I am trying to make a chained Eloquent query on Laravel and bring the users from a users table with a conditional and that is, if they belong to determined house. I am struggling a little to find the way to get that to work. Can someone help me?
This is my controller method:
public function create(){
if(Auth::user()->role->id == 1){
$house = House::findOrFail(Auth::user()->house->id);
$jobs = Job::pluck('name', 'id')->all();
$categories = Category::pluck('name', 'id')->all();
$users = User::pluck('name', 'id')->where('house_id', $house)->get();
return view('admin.tasks.create', compact('jobs', 'categories', 'users'));
}else{
return redirect('home');
}
}
The error been thrown to me when using the get() is:
Type error: Too few arguments to function Illuminate\Support\Collection::get(), 0 passed in /Applications/MAMP/htdocs/Housing_around/app/Http/Controllers/AdminTasksController.php on line 55 and at least 1 expected
And as thought, the all()
in the end doesnt bring me anything in the returned array
Does someone have a clue on how to proceed?
Thank you!
Use the correct syntax to avoid the error:
$jobs = Job::pluck('name', 'id');
$categories = Category::pluck('name', 'id');
$users = User::where('house_id', $house)->pluck('name', 'id');
A suggestion I would give you is to use policies to determine roles for the current authenticated user. If you think that this method in your controller its handling authorization, fetching data from database and passing them to the view.
When the controller role its just a bridge between models(data structure) and presentation (views)
Check out Laravel authorization.
Then pluck()
method its a method that under the hood it calls get()
so you cant call them both at the same time. Same for all()
vs get()
all has get method calling behind the scenes.
So do like $users = User::where('house_id', $house)->pluck('name', 'id');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With