27

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,136
  • 6
  • 29
  • 45
  • 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

54

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
  • 55,020
  • 14
  • 133
  • 137
  • @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
6

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
  • 8,702
  • 9
  • 60
  • 97
5

may be you search this?

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

Easiest to read for me is:

$user->tasks()->exists();
Marcus Christiansen
  • 2,759
  • 6
  • 38
  • 78
-3

You can use the code below:

$user = User::find(1);

$hasTask = $user->tasks()->where('task_id', $taskId)->exists();
louisfischer
  • 1,848
  • 1
  • 20
  • 37
pumpum
  • 473
  • 2
  • 5
  • 15