Laravel query builder with pivot table
UPDATED:
You can do it like this using Laravel's query Builder method - whereHas()
:
Your models should look like this (Many to Many Relationships):
Tour Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tour extends Model
{
public function countries() {
return $this->belongsToMany('App\Country');
}
}
and Country Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Country extends Model
{
public function tours() {
return $this->belongsToMany('App\Tour');
}
}
and now you can fetch the desired results by using the below query:
Tour::where('featured', 1)
->whereHas('countries', function($q) {
$q->where('id', 1);
})
->get();
This will get you the collection of tours with featured = 1
and having country with id = 1
.
Hope this helps!