2
votes

Today I dealt with implementing Laravel's hasMany relation in a pivot model. In my example several vehicles are assigned to a mission through a n:m relationship. Since it's necessary to protocol the vehicles' status, the pivot table hasMany logs.

enter image description here

To attach a relationship it's necessary to implement a pivot model. Take a look here for further information: How to define custom pivot models in Laravel

Our pivot model should look like:

class MissionVehicle extends Pivot
{
    public function logs() {
        return $this->hasMany(Log::class, 'mission_vehicle_id');
    }
}

Since Laravel only attaches the created_at and updated_at attributes automaticallt, it's necessary to attach the id in withPivot method:

public function vehicles() {
        return $this->belongsToMany(Vehicle::class)
            ->withPivot(['id']) // important!
            ->using(MissionVehicle::class);
    }

Now your relationship should work.

1
Your code looks correct could you share your controller code, where these are being used/created - Marcus
I've updated my post. - Lairg

1 Answers

1
votes

Using the ->first()->pivot will give you the intermediate model, I am guessing that that is not what you are after.

$mission = Mission::find(1);
$vehicle = $mission->vehicles()->first();

Should return the first vehicle that belongs to the pivot. If you want that to return info from the intermidiate use

$mission->vehicles()->withPivot(['description'])->first();

Or directly in the relation

public function vehicles() {
    return $this->belongsToMany(Vehicle::class)
        ->using(MissionVehicle::class)->withPivot(['description']);
}