akogler
103
3
Laravel

Map Eloquent event to a dedicated classes and get the ID of the logged in user

Posted 1 year ago by akogler

I'm trying to find out how I could access the logged in users ID in the handle method of the listener.

This is how the listener looks like:

namespace App\Listeners;

use App\Events\ProjectWasDeleted;

class DeleteUserProjectMapping
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  ProjectWasDeleted  $event
     * @return void
     */
    public function handle(ProjectWasDeleted $event)
    {
        $project = $event->project->toArray();

        var_dump($project['id']); // This is working.
        
    }
}

This is how the event:

namespace App\Events;

use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;

class ProjectWasDeleted
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $project;

    /**
     * Create a new event instance.
     *
     * @param $project
     */
    public function __construct($project)
    {
        $this->project = $project;

    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}

The user id is necessary as I would like to delete in a pivot table a record that requires the user id & the project id.

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.