user947668
user947668

Reputation: 2718

Laravel 5.1 event fire

I'm firing event and passing object with array like this:

$event = new App\Events\SendMessage;
$event->msg = [ 'sender_id'=>'191', 
                'recepient_id'=>'190',
                'text'=>'some text',
              ];
Event::fire($event);

Is it possible to make this call a bit shorter and fire event in one line like this?

Event::fire(new App\Events\SendMessage([
                        'sender_id'=>'191', 
                        'recepient_id'=>'190',
                        'text'=>'some text',
                    ]));

Upvotes: 1

Views: 1179

Answers (4)

Pawan Kumar
Pawan Kumar

Reputation: 762

you can fire event like this in laravel

just put the code into your controller

event(new App\Events\EventClassName());

if your Event has parameters then

event(new App\Events\EventClassName(['first' => 'value','second' => 'value']));

Upvotes: 0

The Alpha
The Alpha

Reputation: 146191

In your App\Events\SendMessage you need to define a constructor method for example:

namespace App\Events;

class SendMessage {

    protected $data = null;

    public function __construct(Array $data)
    {
        $this->data = $data;
    }
}

Upvotes: 1

John Svensson
John Svensson

Reputation: 392

Yep. Just pass the data in the __construct()

class SendMessage extends Event
{
    protected $data;
    public function __construct(array $data)
    {
        $this->data = $data;
    }
}

Upvotes: 1

David Boskovic
David Boskovic

Reputation: 1519

You would just need to make sure your event constructor is setup to populate that field.

See: http://laravel.com/docs/5.1/events#defining-events

<?php

namespace App\Events;

use App\Events\Event;
use Illuminate\Queue\SerializesModels;

class SendMessage extends Event
{
    use SerializesModels;

    public $msg;
    public function __construct($msg)
    {
        $this->msg = $msg;
    }
}

Upvotes: 2

Related Questions