Laravel: find if a pivot table record exists
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();
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();