phplaravellaravel-5

Return result after the event is fired in Laravel 5.2


My original code is below

/*
   Create the Role
*/  

$result = (new RoleDb())->Create($obj);

if($result["Success"]) {

    /*
    | Get all Modules 
    */

    $Permissions = $this->Module->All($obj->RoleID);
    $list = [];

    /*
    | Prepare the list that will be assigned to Newly created role.
    */

    foreach($Permissions["Data"] as $Permission) {
        $RolePermissionOM = new RolePermissionOM();
        $RolePermissionOM->PermissionID             = $Permission->PermissionID;
        $RolePermissionOM->IsActive                 = $Permission->DefaultPermission;
        $RolePermissionOM->RoleID                   = $result["Data"];
        array_push($list, $RolePermissionOM);
    }

    /*
    | Create default permissions for above created role.
    */

    return $this->RolePermission->CreateDefaultPermissions($list, $result["Data"]);
}

Now, in my application, there are 3 more points where role is being created and instead of code duplication, I though to convert this code into event. SO whenever a role is being created, an Event is being fired to create the permission records for that role.I wrote the below code.

Event::fire(new RoleCreationEvent($result));
// `$result` contains the newly created RoleID.

Question : In my original code, I was able to get the result to check if the permissions are saved correctly or not. How will I do that in case of firing the Event ?

Event Code

class RolePermissionEvent extends Event
{
    use SerializesModels;

    public function __construct($RoleID, $Module, $RolePermission)
    {

        $Permissions = $Module->All($RoleID);
        $list = [];

        foreach($Permissions["Data"] as $Permission) {
            $RolePermissionOM = new RolePermissionOM();
            $RolePermissionOM->PermissionID = $Permission->PermissionID;
            $RolePermissionOM->RoleID       = $RoleID;
            array_push($list, $RolePermissionOM);
        }

        return $RolePermission->CreateDefaultPermissions($list, $RoleID);
    }
}

Solution

    1. Create a listener like it described here https://laravel.com/docs/5.2/events.
    2. Move all your code from constructor to the listener.
    3. Pass an even to the listener that allows it to use event data.
    4. Return 'return $RolePermission->CreateDefaultPermissions($list, $RoleID);' from listener.