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?
Definition of Laravel Pivot Table. A pivot table is defined as the set of values arranged in a table form where every distinct value of the concerned table can be accessed in the form of a spreadsheet, database, and so on. It is available in one or multiple discrete functionalities.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With