Search code examples
mysqllaravelmany-to-manyrelation

Laravel Many to many filter by pivot attributes


I have 2 tables and a pivot table with extra attributes

table cars

id name
1 BMW
2 Mercedes
3 Bugatti

table status

id colors
1 red
2 blue
3 green

car_color pivot

car_id color_id is_stock
1 1 0
1 2 1
1 3 1
3 2 1

this is my relations

    //  Car model
    public function colors()
    {
        return $this->belongsToMany(Color::class)->withPivot('is_stock');;
    }

    //  Color model
    public function cars()
    {
        return $this->belongsToMany(Car::class)->withPivot('is_stock');;
    }

I want get list of Red BMWs where is_stocks = 1 i do it with mysql query like this

    $red_bmw_stocks = DB::table('car_color')->where('is_stocks ', '1');

how can i convert it to eloquent


Solution

  • $cars = Car::with('colors')->wherePivot('is_stock', 1);