Search code examples
eloquentlaravel-5.3

How to query WhereAnd in Laravel with relationships?


I have a model named Tutorand it has many Subjects hasMany() relationship. I want to write a query that can retrieve all the tutors having subjects Physics and Math.

The table structure of the Subjects is as follows:

id | title | tutor_id

What is the best way to achieve it?


Solution

  • To get all the tutors having subjects Physics and Math both then you can write your query as:

    Tutor::whereHas('subjects', function($q) {
          $q->where('title', 'physics')
        })
        ->whereHas('subjects', function($q) {
            $q->where('title', 'maths')
        })
        ->get();