skip to Main Content

In laravel 11 app User model have defined relation :

namespace AppModels;

use IlluminateFoundationAuthUser as Authenticatable;
...
class User extends Authenticatable
{

    public function uncompletedTasks(): belongsToMany
    {
        return $this->belongsToMany(Task::class)
            ->using(TaskUser::class)
            ->withPivot('supervisor_id')   // Reference to "task_user" table
            ->where('completed', false)
            ->orderBy('priority', 'desc')
            ->orderBy('deadline_at', 'desc');
    }

and when I need to get number of related data I do :

    $this->uncompletedTasksCount = count($this->loggedUser->uncompletedTasks);

I check sql-tracement like:

SELECT `tasks`.*, `task_user`.`user_id`     AS `pivot_user_id`, `task_user`.`task_id`     AS `pivot_task_id`, `task_user`.`supervisor_id`     AS `pivot_supervisor_id`
FROM `tasks`
INNER JOIN `task_user` on `tasks`.`id` = `task_user`.`task_id`
WHERE `task_user`.`user_id` = 1     AND `completed` = ''
ORDER BY `priority` desc, `deadline_at` desc

Question is how can I change my request to get count in sql request(not reading collection of data and php "count" method) to reduce trafik ?

2

Answers


  1. As far as I understand your question, you can do it
    Using withCount method
    $userWithTaskCount = auth()->user()->withCount(['uncompletedTasks']);
    This will add an attribute named uncompleted_tasks_count to your user model, which you can access later.

    OR

    Modifying just modify your Relationship Query
    If you want to include the count directly in the relationship query, you can modify your uncompletedTasks method. However,
    you don’t need to add
    selectRaw('count(*) as uncompleted_tasks_count')
    directly in the relationship method, or simply you use count() on the relationship when needed this is also better approach $count = auth()->user()->uncompletedTasks()->count();
    which will return the count of uncompleted tasks without loading the entire collection of tasks.

    Login or Signup to reply.
  2. Pls simply do this:

     $this->uncompletedTasksCount = $this->loggedUser->uncompletedTasks()->count();
    

    For more information pls check out the sections of querying relations and aggregations in the docs.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search