31

I have two models which are joined by a pivot table, User and Task.

I have a user_id and a task_id.

What is the neatest way to check whether a record exists for this combination of user and task?

datavoredan
  • 3,536
  • 9
  • 32
  • 48
  • 3
    I hope this will be solution http://stackoverflow.com/questions/24555697/check-if-belongstomany-relation-exists-laravel – Ayaz Ali Shah Feb 09 '16 at 07:11

5 Answers5

62

You have a couple options depending on your situation.

If you already have a User instance and you want to see if it has a task with a certain id, you can do:

$user = User::find(1);
$hasTask = $user->tasks()->where('id', $taskId)->exists();

You can reverse this if you have the Task instance and want to check for a user:

$task = Task::find(1);
$hasUser = $task->users()->where('id', $userId)->exists();

If you just have the ids, without an instance of each, you could do the following:

$hasPivot = User::where('id', $userId)->whereHas('tasks', function ($q) use ($taskId) {
        $q->where('id', $taskId);
    })
    ->exists();
patricus
  • 59,488
  • 15
  • 143
  • 145
  • @patricus, Seems you can help me. Look at this : https://stackoverflow.com/questions/44519339/how-can-i-update-pivot-table-on-laravel – moses toh Jun 13 '17 at 10:59
  • In my case, what works, considering your example table and column names is: `$user->userTasks()->where('task_id', $taskId)->exists();` but it depends on definition inside of the model files, of course. – Banik Oct 12 '22 at 10:55
8

You can also try this, this is working in Laravel 5.7

$user = User::find(1);
$hasTask = $user->tasks->contains($taskId);

But the better way will be

$hasTask = $user->tasks()->where('tasks.id', $taskId)->exists();
Prafulla Kumar Sahu
  • 9,321
  • 11
  • 68
  • 105
6

may be you search this?

$users = User::has('task')->get();
Yurich
  • 577
  • 3
  • 17
1

Easiest to read for me is:

$user->tasks()->exists();
Marcus Christiansen
  • 3,017
  • 7
  • 49
  • 86
-3

You can use the code below:

$user = User::find(1);

$hasTask = $user->tasks()->where('task_id', $taskId)->exists();
louisfischer
  • 1,968
  • 2
  • 20
  • 38
pumpum
  • 555
  • 3
  • 5
  • 18