Home > Software engineering >  Laravel: the count in the condition always returns 0
Laravel: the count in the condition always returns 0

Time:07-31

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.

To do this I have run the following condition:

$count_project = Project::select('client_id')->where('client_id','$client->id')->count();

return view('client.index', compact('clients', 'count_project'));

public function index()
    {
        $clients = Client::all();
        $count_project = Project::select('client_id')->where('client_id','$client->id')->count();
        return view('client.index', compact('clients', 'count_project'));
    }

where in the last line I pass the variable to the corresponding view.

There is certainly an error in the condition written above.

Can anyone kindly help me?

CodePudding user response:

The problem with your code is that you are getting a collection of clients, not a single client. Assuming you have the relationship setup, a cleaner way is

        $clients = Client::withCount('projects')->get();

        return view('client.index', compact('clients'));

now each client, when you loop over them will have an extra attribute projects_count

https://laravel.com/docs/9.x/eloquent-relationships#counting-related-models

  • Related