Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: find if a pivot table record exists

Tags:

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?

like image 637
datavoredan Avatar asked Feb 09 '16 07:02

datavoredan


People also ask

What is pivot table in laravel?

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.


1 Answers

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(); 
like image 159
patricus Avatar answered Oct 23 '22 14:10

patricus