Using hooks
Created 6 years ago by squattoThe docs show how to use hooks, but they aren't very clear on where to put the code. Does anybody have some practical examples of code to use hooks on a model?
I was able to get this working by adding the following to a module service provider:
public function boot(UserModel $user)
{
if (method_exists($user, 'bind')) {
$user->bind('producer', function() {
return $this->belongsTo(ProducerModel::class, 'producer_id');
});
$user->bind('get_producer', function() {
return $this->producer()->first();
});
}
}
This allowed me to do the following in a twig template: user().producer.display_name
There are other ways to do this, which @edster is going to show us...
So it depends really I'll give an example of attaching a profile (realtors) relation to the user model.
In my service providers boot
method I have added
$this->dispatch(new AttachRealtorRelationToUser());
That class does this
class AttachRealtorRelationToUser {
public function handle()
{
$user = new UserModel();
/* @var Hookable $user */
if (!method_exists($user, 'bind')) {
return;
}
/**
* Get the user's realtor profile.
*
* @return \Illuminate\Database\Eloquent\Relations\hasOne
*/
$user->bind(
'realtor',
function () {
/* @var UserModel $this */
return $this->hasOne(RealtorModel::class, 'user_id');
}
);
}
}
I generally put them in service providers (PRO link): https://github.com/anomalylabs/social-module/blob/1.0/src/SocialModuleServiceProvider.php#L95
You can add them anywhere there. I've added them on tables / forms from controllers and even from things like a buttons handler for a table. So anywhere in runtime - the need kinda dictates the where.
So it depends really I'll give an example of attaching a profile (realtors) relation to the user model.
In my service providers
boot
method I have added$this->dispatch(new AttachRealtorRelationToUser());
That class does this