I have two tables, one named Clients and the other named Projects linked together via a foreign key (this is client_id, present in Projects).
In the view related to the list of all clients, I have an additional field that shows me the number of active projects for each client.
So far everything ok! When I click on the number of active projects, I am shown all the projects while I only want those related to that client. So I believe the error is in the condition. (the withCount below is used to provide me with the number of tasks present in each project)
public function index($id)
{
$projects = Project::withCount(['tasks'=> function (Builder $query) use ($id){
$query->where('client_id', $id);
}])->get();
return view('project.index', compact('projects'));
}
There is certainly an error in the condition written above.
Can anyone kindly help me?
CodePudding user response:
Project::where('client_id', $id)->withCount('tasks')->get();
You were trying to find the client_id inside the tasks
CodePudding user response:
Assuming you have some kind of route that is /client/{client}/projects
You can pass the client into the controller using Route Model binding, and call the projects relationship directly:
public function index(Client $client) {
$client->projects()->get();
}