Search code examples
laravellaravel-8eloquent-relationship

Create a New Model (Polimorphic) based on some of the fields of another just created Model - Laravel 8


I'd like to make an enhancement of the code, that actually feels a mess.

When I create a User that has an 'email' field. I also need to create an Email model (Polymorphic) based on that same data.

Actually the UserController's "store" method looks a little big. So, is there another way of hooking the creation event, and then create the Email. Here is how I'm doing now:

$user = User::make($request->safe()->except('active', 'is_contact', 'groups', 'password'));
$user->password = Hash::make($request->password);
$user->active = (!empty($request->active)) ? 1 : 0;
$user->is_contact = (!empty($request->is_contact)) ? 1 : 0;
$user->save();

$this->saveEmail($user);

And the saveEmail:

private function saveEmail($user)
{
    $email = new Email;
    $email->fill([
        'email' => $user->email,
        'email_type' => 'primary',
        'main' => 1,
    ]);

    $user->emails()->save($email);
}

So, is there another way of doing this outside of the controller? Thanks anyway. Hernán.


Solution

  • There is a cleaner way to do this which is using the laravel observer. you can do it in 2 ways:-

    first way,adding creating function in the user model which will fire everytime a user is created

    public static function boot() {
        parent::boot(); 
        //once created/inserted successfully this method fired, so I tested foo 
        static::created(function (User $user) {
           $email = new Email;
           $email->fill([
               'email' => $user->email,
               'email_type' => 'primary',
                 'main' => 1,
           ]);
           $user->emails()->save($email);  
        });
    }
    

    second you can make in a seperate observer class see the link :- https://laravel.com/docs/8.x/eloquent#observers