mercredi 1 juin 2016

Overriding attach method from belongsToMany relationship

I want to add an attribute on a pivot table on every attach/save in a belongsToMany relationship.

Example:

// I don't want to do add the `rand` attribute everytime...
User::find(1)->roles()->save($role, ['rand' => rand()]);
User::find(7)->roles()->save($role, ['rand' => rand()]);
User::find(42)->roles()->save($role, ['rand' => rand()]);

// ... I just want to call save...
User::find(1)->roles()->save($role);
// ... and magically, `rand` attribute is set to rand()

I wanted to overload belongsToMany function in Model, but it does not look like to be a good solution, it looks like a hack. Because doing this, I have to create a new BelongsToMany class extending the original one, call the original attach method in Model, then override the returned object, and then my code becomes spaghetti, so I threw everything.

Is there any elegant way to do this?

Side note: rand attribute is a stupid example, it's just an illustration, don't care about it.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire