Reputation: 299
i'm trying to get all the lead_id inside my pivot table but i can't make it work.
controller:
$levels = Level::all();
$levels->lead()->attach('lead_id');
return $levels;
Model Level:
public function lead(){
return $this->belongsToMany(Lead::class, 'level_students')->withPivot('level_id', 'lead_id');
}
Model Lead:
public function level(){
return $this->belongsToMany(Level::class, 'level_students')->withPivot( 'lead_id', 'level_id');
}
Upvotes: 0
Views: 4709
Reputation: 301
If you mean all lead_id
of a Level
, then you can use pluck()
.
$level->lead->pluck('lead_id');
I'm not really sure what you are trying to achieve because it seems that you want to retrieve all lead_id
associated with any Level
. But if that is the case, then you can create a model for the pivot table (e.g. LevelLead
) and use distinct()
or with Query Builder:
$leadIds = DB::table('level_students')->select('lead_id')->distinct()->get();
If you want to get the referenced table's column (e.g. leads
table's name
column) then you can use JOIN. Check Laravel's doc for more options. For example, assuming the table name for Lead
is leads
, then:
$leads = DB::table('level_students')->join('leads', 'level_students.lead_id', '=', 'leads.lead_id')->select('level_students.lead_id', 'leads.name')->distinct()->get();
Upvotes: 2