如何从控制器调用事件?命名空间

时间:2019-12-05 13:08:14

标签: php laravel laravel-5 namespaces laravel-5.8

我试图建立通知系统。 我创建了事件:


namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class DealApproved implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $username;

    public $message;

     public function __construct($username)
    {
        $this->username = $username;
        $this->message  = "{$username} approved your deal#50. Please take an action!";
    }


    public function broadcastOn()
    {
         return ['notification-channel-4'];

    }



}

我的路线:

Route::get('/notify', 'NotificationController@approve_deal');

我的控制器:

<?php



namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Pusher\Pusher;
use Events\DealApproved;

class NotificationController extends Controller
{
    public function approve_deal()
    {


            event(new App\Events\DealApproved('Someone'));


    return "Event has been sent!";



    }
}

当我使用此路线时:

Route::get('notify', function () {
    event(new App\Events\DealApproved('Someone'));
    return "Event has been sent!";
});

一切正常,但是当我更改到控制器的路由时出现错误:

找不到类'App \ Http \ Controllers \ App \ Events \ DealApproved'

使用Events \ DealApproved;没有工作,请帮助

1 个答案:

答案 0 :(得分:1)

只需将此行放入控制器use App\Events\DealApproved;

并更改此

   event(new DealApproved('Someone'));

应该可以。