DrRamazzotti's avatar

Custom pivot model

Hi @all,

I have a many-to-many relation with additional pivot fields.

<?php

namespace App\Models;

use App\Events\EventCreated;

class Event extends BaseModel
{
    /**
     * 
     *
     * @return \Illuminate\Database\Eloquent\Relations\belongsToMany
     */
    public function guests(): \Illuminate\Database\Eloquent\Relations\belongsToMany
    {
        return $this->belongsToMany(Guest::class)->using(GuestEvent::class)->withTimestamps();
    }
}

The custom pivot model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\Pivot;

class GuestEvent extends Pivot
{
    public function arrival(): HasOne
    {
        return $this->hasOne(Travelinformation::class);
    }
}

How to add in the query the arrival? (->with('arrival') ) => eager loading

$event = Event::query()->first();
        $data = $event->guests()->withPivot(['function', 'arrival', 'departure']);

0 likes
4 replies
DrRamazzotti's avatar

Hi aletopo,

thanks for your reply. Will try it out if it works also on pivot table.

Bernhard

DrRamazzotti's avatar

Hi aletopo,

maybe I did something wrong, but for me it's not working on pivot table...

kevinbui's avatar

I have just checked the source code, the Illuminate\Database\Eloquent\Relations\Concerns\InteractsWithPivotTable trait. I don't think that is possible.

What do you need that for?

Please or to participate in this conversation.