Skip to content
Advertisement

Laravel: find if a pivot table record exists

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?

Advertisement

Answer

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();
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement