Farshad
Farshad

Reputation: 2000

how to query whereHas on a belongs to many relationship using laravel

hi i am having a User and Task model and they have a many to many relation ship like below i added :

 public function users()
    {
        return $this->belongsToMany(User::class,'user_tasks');
    }

and in my user model :

 public function tasks()
    {
        return $this->hasMany(Task::class);
    }

and in my controller i want to get the task that are assigned to the logged in user like below :

   $task = Task::whereHas('users', function(Builder $query){
            $query->where('id',Auth::user()->id);
        })->get();
        dd($task);

but i get this error :

SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous (SQL: select * from `tasks` where exists (select * from `users` inner join `user_tasks` on `users`.`id` = `user_tasks`.`user_id` where `tasks`.`id` = `user_tasks`.`task_id` and `id` = 4))

and when i change the id to users.id i get empty value but when i load it like below :

$task = Task::with('users')->get();

i get all the task with the relationships and they are working well but with whereHas its not working thanks in advance

Upvotes: 1

Views: 1421

Answers (2)

OMR
OMR

Reputation: 12188

why not just:

$userTasks=Auth::user()->tasks;

this will get the current user tasks.

Upvotes: 2

lagbox
lagbox

Reputation: 50491

Since you are dealing with the pivot table with this relationship you can use the pivot table field user_id to filter:

$task = Task::whereHas('users', function (Builder $query) {
    $query->where('user_id', Auth::user()->id);
})->get();

Upvotes: 3

Related Questions