Skip to content
Advertisement

Laravel polymorphic with custom foreign key

I have problem with custom shipmentable_type. My structure looks like this:

transfers:
id - integer
name - string

shipment:
id - integer
name - string

shipmentale:
shipment_id - integer
shipmentable_id - integer
shipmentabl_type - enum ( transfer, order, complaint, internet )

Now I have in my Transfer model realtion like this:

 public function shipments()
{
    return $this->morphToMany(Shipment::class, 'shipmentable');
}

The problem is, that to table shipmentable, to column shipmentable_type is going sth like this now: App/Models/Transfer, but I would like to force to be there ‘transfer’ in this case. Is it possible?

Advertisement

Answer

From the docs

By default, Laravel will use the fully qualified class name to store the type of the related model. However, you may wish to decouple your database from your application’s internal structure. In that case, you may define a relationship “morph map” to instruct Eloquent to use a custom name for each model instead of the class name:

use IlluminateDatabaseEloquentRelationsRelation;

Relation::morphMap([
   'transfer' => 'App/Models/Transfer'
]);

You may register the morphMap in the boot function of your AppServiceProvider or create a separate service provider if you wish.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement