Search code examples
phplaraveleventslaravel-9laravel-events

How to return the result from listener to the Controller


I'm working with Laravel 9 and I have called this event in my Controller method when a new user signs up and registers:

$data = $request->validated();

event(new RegisterNewUserEvent($data));

$code = ActiveCode::generateCode($user);
dd($code);

So the RegisterNewUserEvent event will create a new record by calling this listener:

public function handle(RegisterNewUserEvent $event)
    {
        $firstName = $event->data['fname'];
        $lastName = $event->data['lname'];
        $userName = $event->data['uname'];
        $mobilePhone = $event->data['phone'];
        $hashPassword = Hash::make($event->data['password']);
        $randomString = Str::random(20);

        $user = User::create([
            'usr_first_name' => $firstName,
            'usr_last_name' => $lastName,
            'usr_user_name' => $userName,
            'usr_mobile_phone' => $mobilePhone,
            'usr_password_hash' => $hashPassword,
            'usr_str' => $randomString,
        ]);

        $event->data = $user->id;
    }

So it stores the new created user at $user object and back to the Controller method, I need this object for returning the activation code like this:

$code = ActiveCode::generateCode($user);

But I don't know, how to get the $user object from the event listener and call it again at the Controller method!

So if you know, please let me know...


Solution

  • In my opinion, the usage of events here is incorrect.

    Events/Listeners can be used after a specific event has happened to execute a function based on that event.

    For example, After a new user registers, send them a welcome email.

    So, you'll have an event that is called NewUserRegistered which gets broadcasted whenever the registration is completed. And for that event, you'll have a listener (or more) that is called SendWelcomeEmail.


    In your case, I think you have them in reverse.

    From my understanding, you want to generate some kind of code for a newly registered user.

    So, you can have the logic to register a user in your controller (or maybe a service class if the logic is being used in multiple controllers/places) and then an event that gets broadcasted after the registration process has completed which will have a listener to execute the generate active code piece of logic that you have. That way, you can accept the newly registered user as a param in the event and have access to it in the listener.

    I hope this helps. Let me know if I haven't understood your question correctly and I'll update my answer accordingly.