Search code examples
laraveleloquentmany-to-many

Laravel - Get additional attributes of Many to Many table


I got the following tables

  • actors
    1. id
    2. name
  • stats
    1. id
    2. name
  • actor_stat
    1. actor_id
    2. stat_id
    3. quantity

I want, given an actor's name, take all the quantities associated.

Actor model:

class Actor extends Model
{
    public function stats()
    {
        return $this->belongsToMany('App\Stat', 'actor_stat')->withPivot('quantity');
    }

}

Stat model:

class Stat extends Model
{
    public function users()
    {
        return $this->belongsToMany('App\User', 'actor_stat')->withPivot('quantity');
    }
}

Query

    public function request(){
        $actors = Actor::where('name','Jack')->first();

        $stat = $actors->pivot->quantity; //??

        return response()->json(['actors' => $actors, 'stat' => $stat]);
    }

Suggestions?


Solution

  • you can use eager loading to load related table like this:

    $actors = Actor::with('stats')->where('name','Jack')->first();
    
    //do loop foreach actor state then you can access to quantity column
    
     foreach($actors->states as $state)
       $state->pivot->quantity;