How to add custom event to a laravel model?

by darrion.kuhn , in category: PHP Frameworks , 24 days ago

How to add custom event to a laravel model?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by shyann , 23 days ago

@darrion.kuhn 

To add a custom event to a Laravel model, you can use Laravel's built-in event system. Here's how you can do it:

  1. Define the custom event in your model class by adding a protected $dispatchesEvents array property. This property should map the event name to the corresponding event class.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
namespace App;

use IlluminateDatabaseEloquentModel;
use AppEventsCustomEvent;

class YourModel extends Model
{
    protected $dispatchesEvents = [
        'custom_event' => CustomEvent::class,
    ];

    // Your model code here
}


  1. Create the custom event class by running the following command in your terminal:
1
php artisan make:event CustomEvent


This will create a new event class under the App/Events directory.

  1. In the custom event class, you can define any logic that you want to execute when the event is triggered. For example, you can send an email or log a message.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
namespace AppEvents;

use IlluminateFoundationEventsDispatchable;
use IlluminateQueueSerializesModels;

class CustomEvent
{
    use Dispatchable, SerializesModels;

    public function __construct()
    {
        // Constructor logic here
    }
}


  1. Trigger the custom event in your controller or other parts of your application by using the dispatch method:
1
2
3
use AppYourModel;

YourModel::find(1)->event(new CustomEvent());


That's it! Now, when the custom_event is triggered on a YourModel instance, the CustomEvent class will be executed.