Reputation: 5829
I am using the default user registrar in Laravel 5. When the user registers there is some information stored in the session so after the user has been created I want to run some code to process the session data, store it and link it to the user. Would I just amend the create method in the registrar from this:
public function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password'])
]);
}
to this:
public function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password'])
]);
// do my other logic to process session data here
return $user;
}
Or is there a better way to do it?
Upvotes: 4
Views: 3176
Reputation: 9454
You can use a model event, place this code in your model.
public static function boot()
{
static::created(function($model)
{
//do other logic here
});
}
http://laravel.com/docs/5.0/eloquent#model-events
You can also opt for a model observer:
<?php namespace App\Observers;
use Illuminate\Database\Eloquent\Model as Eloquent;
class UserObserver {
public function created(Eloquent $model)
{
//do other logic
}
}
You'll need a listener to this observer:
\App\User::observe(new \App\Observers\UserObserver);
You can place the listener in the routes.php
file to test it.
Later on you can move the listener to a more appropriate location such as a ServiceProvider
.
http://laravel.com/docs/5.0/eloquent#model-observers
Upvotes: 4