Search code examples
laraveleloquentlaravel-8laravel-9

I get all the projects while I only want the projects related to that client


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?


Solution

  • Project::where('client_id', $id)->withCount('tasks')->get();
    

    You were trying to find the client_id inside the tasks