将Eloquent事件映射到专用类并获取登录用户的ID

时间:2018-01-03 11:12:38

标签: laravel laravel-5 eloquent laravel-eloquent

我正在尝试了解如何在侦听器的handle方法中访问登录用户ID。

这是听众的样子:

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.

    }
}

这就是事件:

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');
    }
}

用户ID是必要的,因为我想在数据透视表中删除需要用户ID&项目编号。

1 个答案:

答案 0 :(得分:1)

您可以使用以下方式全局访问当前用户实例:

auth()->user()

获取ID:

auth()->id()

或者:

auth()->user()->id