Whenever I create a "user", I have to create a line in different tables (like account). I know that in the controller I can create the user and account like this:
$user = User::create($user_inputs);
$account = $user->account()->create($account_inputs);
$OtherTables...
Is there a way to do this in the model? Always when someone creates a user from another controller, will the lines be automatically inserted in the other tables. Or is it always necessary to indicate it in the controller every time?
CodePudding user response:
You can use model events for this. https://laravel.com/docs/9.x/eloquent#events-using-closures
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The "booted" method of the model.
*
* @return void
*/
protected static function booted()
{
// This code will be called every time a new user is inserted into the system
static::created(function ($user) {
$user->account()->create([ 'name' => $user->name ])
});
}
}
There are few more events you can use within booted method, the name tells clearly what they do.
creating
created
updating
updated
saving
saved
deleting
deleted
CodePudding user response:
You can use Laravl observer
<?php
namespace App\Observers;
use App\Models\User;
class UserObserver
{
/**
* Handle the user "created" event.
*
* @param \App\User $user
* @return void
*/
public function creating(User $user)
{
$user->account()->create([
// your data
]);
}
}