Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if one record is attached to another?

I have defined a many-to-many relationship between Student and Seminar models. How can I find out if one particular student is attending one particular seminar? Non-working example of what I want to achieve is illustrated below:

$seminar->students()->contains($student->id);

The following error is shown when using the above code snippet:

BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder::contain()'

like image 700
Alex Lomia Avatar asked May 10 '16 14:05

Alex Lomia


1 Answers

Try instead:

$seminar->students->contains($student->id);

Presuming $student contains an instance of the Student model you can simplify it further and just use:

$seminar->students->contains($student);

When you add parentheses you're using the Laravel query builder, and you never completed the query. To do it in the manner you had originally you would need:

$seminar->students()->get()->contains($student->id);

This method could be useful if you wanted to add constraints when fetching your students.

But generally you can omit the parentheses and a Collection will be returned, allowing you to use methods like contains.

This has the additional benefit of not re-querying the database once the relationship is loaded, so will generally be a far more efficient means of fetching relationships.

If you haven't already loaded the students and want a database efficient method of checking you could instead use:

$seminar->students()->where('students.id', $student->id)->exists();
like image 185
Matt McDonald Avatar answered Oct 12 '22 13:10

Matt McDonald