0
votes

This may be the incorrect way for "Laravel 5.5", but I have a pivot table

buildings_users | building_id, user_id, first_name, last_name

and

users | id, first_name, last_name (don't ask..)

buildings | id, etc...

App\User

public function buildings(){
   return $this->belongsToMany('App\Building');
}

App\Building

public function users(){
   return $this->hasMany('App\User');
}

How can I output the first_name and last_name from the pivot table instead of users table?

I tried

App\User

public function fullName(){

        $user = $this->select('bu.first_name','bu.last_name')->join('buildings_users as bu','bu.user_id','=','users.id')->where('bu.building_id','=',$this->current_building())->where('bu.user_id','=',$this->id)->first();

        if(!empty($user)):
            return $user;
        else:
            return array("first_name"=> "N/A","last_name"=>"");
        endif;

    }

Which works when I do $user->fullName()->first_name & last_name, however, I can't do lazy loading via

$user->load('fullName')

because I cannot "add EagerConstraints to Array".

--

What should be done to get the functionality I'm hoping for, besides having to join on every controller query instance.. Do I really have to have a new table like buildings_users_names ... and use it as another relation?

1

1 Answers

2
votes

When declaring your relation between those models, you can specify which fields from the pivot table want to be accessible:

App\User

public function buildings(){
    return $this->belongsToMany(App\Building::class)
            ->withPivot('first_name', 'last_name');
}

Then you can use it like

@foreach($user->buildings as $building)
    <p>{{ $building->pivot->last_name }}, {{ $building->pivot->first_name }} </p>
@endforeach