Laravel Query Builder pivot table connection

Viewed 72

I'm trying to get the all related countries which the country is belongs to the regions it is many to many relation. I want it in the query builder realations

this I pivot table

 id         bigint unsigned auto_increment
        primary key,
    country_id bigint unsigned not null,
    region_id  bigint unsigned not null

Region Model

public function r_countries()
    {
        return $this->belongsToMany(Country::class, "country_regions","region_id","country_id");
    }


Country Model
   public function r_regions(): BelongsToMany
    {
        return $this->belongsToMany(Region::class, "country_regions", "country_id", "region_id");
    }

I tied this it works

$region = \App\Models\Country\Region::findOrFail(23);
$region->r_countries()->pluck("countries.title");
1 Answers

You can use

Model::whereHas('relation_name', function($query) use($varname){
         $query->where(condition);
})->get()
Related