Home > Back-end >  Is it posible in Laravel to set more values with relations "hasMany" automatically?
Is it posible in Laravel to set more values with relations "hasMany" automatically?

Time:07-29

For example, I have model User with relation hasMany LoginHistory :

public function loginHistory(): HasMany
{
    return $this->hasMany(LoginHistory::class);
}

Now I want when user login to create login history and it works like this :

$user->loginHistory()->create(['user_email' => $user->email]);

Now my question is can I somehow create login history record in database without adding attributes user_email in create method.

What I want to achieve is that when I call just create method like below this to automatically fill user_email because it looks more clean in code, and also it would make more sense because there is relation, than adding again from same user email to fill login_histories.

$user->loginHistory()->create();

CodePudding user response:

I see 2 options.

  1. Make a method on the User model to create a LoginHistory.
# User.php

public function createLoginHistory(): LoginHistory
{
    return $this->loginHistory()->create(['user_email' => $this->email]);
}
$user->createLoginHistory();
  1. If the user is always going to be the authenticated user, you could add it using the creating hook for the LoginHistory model.
# LoginHistory.php

public static function booted()
{
    static::creating(function (LoginHistory $loginHistory) {
        $loginHistory->user_email = Auth::user()->email;
    });
}
$user->loginHistory()->create();
  • Related