SaidbakR
SaidbakR

Reputation: 13544

Laravel eloquent UUID in a pivot table

This question is like this one: laravel uuid not showing in query. However, the difference in this question is about that table is a pivot table with id field uses UUID generated via MySQL trigger on insert.

I don't want to create another model for that pivot table to supply it with the solution regarded on the similar question's answer. So, is there any way to perform type casting of the pivot table from another model related to it?

Upvotes: 3

Views: 6257

Answers (3)

Matthias Schobner
Matthias Schobner

Reputation: 1240

Since Laravel 9 you can pass the trait HasUuids to new instances:

    /**
     * @return BelongsToMany<\App\Models\ExampleModel>
     */
    public function tags(): BelongsToMany
    {
        return $this
            ->belongsToMany(\App\Models\ExampleModel::class)
            ->using(new class extends \Illuminate\Database\Eloquent\Relations\Pivot; {
                use \Illuminate\Database\Eloquent\Concerns\HasUuids;
            });
    }

An alternative is to create a pivot class and set this use statement there. However, this was excluded by the questioner.

Upvotes: 3

Alexander
Alexander

Reputation: 1

It works for me:

// use Illuminate\Database\Eloquent\Relations\Pivot;
return $this->belongsToMany(Vendor::class, 'vendors_has_geo_cities', 'city_id', 'vendor_id')
            ->using(new class extends Pivot {
                use UuidTrait;
            });
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

trait UuidTrait
{
    public function initializeUuidTrait(): void
    {
        $this->setIncrementing(false);
        $this->setKeyType('string');
    }

    /**
     * The "booting" method of the model.
     *
     * @return void
     */
    protected static function bootUuidTrait()
    {
        self::creating(function (Model $model) {
            $model->setAttribute($model->getKeyName(), Str::orderedUuid());
        });
    }
}

Upvotes: 0

Ramy Tamer
Ramy Tamer

Reputation: 640

I think this might be what you want:

In your model that defines the BelongsToMany relationship add this property:

protected $casts = ['relationName.pivot.id' => 'string'];

Update

I guess we can make use of anonymous classes in php7.0 here instead of creating a model class for the pivot:

i didn't test this code so i don't know if it will work or not, this is just an idea

public function activeStatuses()
{
    return $this->belongsToMany('ModelName')
                ->using(class_basename(new class extends \Illuminate\Database\Eloquent\Relations\Pivot {
                    protected $casts = ['id' => 'string'];
                }));
}

Generally i would prefer to create model for the pivot table or simply use a pivot class

Upvotes: 2

Related Questions