How to execute save in a laravel listener?

by cali_green , in category: PHP Frameworks , 5 months ago

How to execute save in a laravel listener?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by addison , 5 months ago

@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. Create your Listener class by running the following command in your terminal:
1
php artisan make:listener SaveUser


This command will create a new Listener class named SaveUser in the app/Listeners directory.

  1. Open the SaveUser class and implement the handle method. Within the handle method, you can access the model instance and execute the save operation. Here is an example:
 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. Register the Listener in the EventServiceProvider. Open the EventServiceProvider class (app/Providers/EventServiceProvider.php) and add the Listener to the $listen array:
1
2
3
4
5
protected $listen = [
    'AppEventsUserSaved' => [
        'AppListenersSaveUser',
    ],
];


  1. Trigger the event from anywhere in your application where you want to save the user. For example, you can trigger the event in a UserController:
 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.