sheikhuzairhussain's avatar

Model create method overriding doesn't work when called through a relationship

Hi.

I am working on a large website that includes e-commerce along with many other things. E-commerce-related methods and relationships have been bundled into custom classes (referred to as modules) that extend the existing models. There is a User module and an Address module (the user's shipping address).

I'm trying to override the built-in create method in the Address module with a custom create method defined in the Address module.

But, when I execute \App\Modules\Ecommerce\User::find($id)->addresses()->create($data), my custom create method is not executed. Instead, Eloquent's own create method is being executed.

Side note: The create method returns an instance of the App\Modules\Ecommerce\Address, which is the desired behavior. The get method also returns a collection of App\Modules\Ecommerce\Address instances.

Any help would be appreciated. Thank you.

This is my User module:

namespace App\Modules\Ecommerce;

class User extends  \App\Models\User
{
    public function addresses()
    {
        return $this->hasMany(Address::class);
    }
}

and this is my Address module:

namespace App\Modules\Ecommerce;

class Address extends \App\Models\Address
{
	public function create($data)
	{
		dd("This is never executed.");
	}
}
0 likes
1 reply
bobbybouwmann's avatar

You can't override the create method since the create method is not being called on the model. If you want to do something extra with the data on create you should hook into the model events and perform your action.

You can read more about it here: https://laravel.com/docs/8.x/eloquent#events

Let me know if anything is unclear.

Please or to participate in this conversation.