@cali_green
In Laravel, you can execute a save operation within a listener by accessing the model instance passed to the listener's handle method and using the save method on that model. Here is an example of how you can execute a save operation in a Listener:
1
|
php artisan make:listener SaveUser |
This command will create a new Listener class named SaveUser in the app/Listeners directory.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
namespace AppListeners;
use AppEventsUserSaved;
class SaveUser
{
public function handle(UserSaved $event)
{
// Access the user model instance passed to the event
$user = $event->user;
// Perform the save operation
$user->save();
}
}
|
1 2 3 4 5 |
protected $listen = [
'AppEventsUserSaved' => [
'AppListenersSaveUser',
],
];
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
namespace AppHttpControllers;
use AppModelsUser;
use AppEventsUserSaved;
class UserController extends Controller
{
public function store()
{
$user = new User();
$user->name = 'John Doe';
$user->email = '[email protected]';
$user->password = bcrypt('password');
$user->save();
event(new UserSaved($user));
return response()->json($user);
}
}
|
With these steps, the save operation on the user model will be executed within the SaveUser listener when the UserSaved event is triggered.