Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 570
wenus Avatar asked Sep 15 '26 21:09

wenus


2 Answers

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 Illuminate\Database\Eloquent\Relations\Relation;

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.

like image 103
Mahdi Younesi Avatar answered Sep 18 '26 11:09

Mahdi Younesi


To set a value other than the model's fully qualified name in shipmentable_type, there is the Relation::morphMap() function.

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

This should be set in the AppServiceProvider or similar.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!