How to create events for created/updated/deleted model task in Laravel 5?

January 10, 2018 | Category : Laravel 5.5 Laravel 5 Laravel PHP

Here, i want to know you how to create Eloquent models events for creating, updating, deleting, retrieved, created, updated, saving, saved, deleted, restoring, restored in PHP Laravel 5. here i will show you simple and quick example for event fire on eloquent model method. Using this tutorial you will learn to create laravel event listener, also can set queue.

Laravel introduce very unique and fantastic feature event for your each task of database. Laravel Events allow you to easily execute code each time a specific model class is saved, updated, deleted, restored etc in the mysql database. If you are new in laravel then you think how to built it but here you can see how it's easy to implement events for each task. It is very useful concept. So you can also add your activity log by using events.

So, here just follow bellow step and get events for created/updated/deleted model task.

Step 1: Create Item Table

First thing is we have to create "items". so we have to create migration for items table using Laravel 5.5 php artisan command, so first fire bellow command:

php artisan make:migration create_items_table

After this command you will find one file in following path database/migrations and you have to put bellow code in your migration file for create items table.

<?php


use Illuminate\Support\Facades\Schema;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Database\Migrations\Migration;


class CreateItemsTable extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

Schema::create('items', function (Blueprint $table) {

$table->increments('id');

$table->string('name');

$table->string('price');

$table->timestamps();

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::dropIfExists('items');

}

}

Next run migration for creating table by following command:

php artisan migrate

Step 2: Create Item Event

In this step we will create event for Item model. So simply run bellow command and create event for Item.

php artisan make:event ItemEvent

Ok, now you have new file in Events folder. So you can see ItemEvent.php file in your Events directory and put bellow code on that file.

app/Events/ItemEvent.php

<?php


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;

use App\Item;

use Log;


class ItemEvent

{

use Dispatchable, InteractsWithSockets, SerializesModels;


/**

* Create a new event instance.

*

* @return void

*/

public function __construct()

{

}


/**

* Get the channels the event should broadcast on.

*

* @return \Illuminate\Broadcasting\Channel|array

*/

public function itemCreated(Item $item)

{

Log::info("Item Created Event Fire: ".$item);

}


/**

* Get the channels the event should broadcast on.

*

* @return \Illuminate\Broadcasting\Channel|array

*/

public function itemUpdated(Item $item)

{

Log::info("Item Updated Event Fire: ".$item);

}


/**

* Get the channels the event should broadcast on.

*

* @return \Illuminate\Broadcasting\Channel|array

*/

public function itemDeleted(Item $item)

{

Log::info("Item Deleted Event Fire: ".$item);

}

}

Step 3: Register Event

Now, we have to register following events on EventServiceProvider.php file. So let's simply open that file and put like as bellow code:

app/Providers/EventServiceProvider.php

<?php


namespace App\Providers;


use Illuminate\Support\Facades\Event;

use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;


class EventServiceProvider extends ServiceProvider

{

/**

* The event listener mappings for the application.

*

* @var array

*/

protected $listen = [

'App\Events\Event' => [

'App\Listeners\EventListener',

],

'item.created' => [

'App\Events\ItemEvent@itemCreated',

],

'item.updated' => [

'App\Events\ItemEvent@itemUpdated',

],

'item.deleted' => [

'App\Events\ItemEvent@itemDeleted',

]

];


/**

* Register any events for your application.

*

* @return void

*/

public function boot()

{

parent::boot();

}

}

Step 4: Create Model

Now we will create morel for "items" table. So just simple create Item.php file and also add events code on boot method:

app/Item.php

<?php


namespace App;


use Illuminate\Database\Eloquent\Model;

use Event;


class Item extends Model

{

protected $fillable = ['name', 'price'];


public static function boot() {


parent::boot();


static::created(function($item) {

Event::fire('item.created', $item);

});


static::updated(function($item) {

Event::fire('item.updated', $item);

});


static::deleted(function($item) {

Event::fire('item.deleted', $item);

});

}

}

Step 5: Add Demo Route

Now we will test following all event like create, update and delete model task. So just simple add following routes:

routes/web.php

Route::get('item-created', function(){

\App\Item::create(['name'=>'test 2', 'price'=>100]);

dd('Item created successfully.');

});


Route::get('item-updated', function(){

\App\Item::find(1)->update(['name'=>'test 3', 'price'=>100]);

dd('Item updated successfully.');

});


Route::get('item-deleted', function(){

\App\Item::find(1)->delete();

dd('Item deleted successfully.');

});

Ok, now we are ready to run following example like as bellow :

http://localhost:8000/item-created

http://localhost:8000/item-updated

http://localhost:8000/item-deleted

Then you will find in your log file like as bellow:

storage/logs/laravel.log

[2018-01-10 04:08:30] local.INFO: Item Created Event Fire: {"name":"test 2","price":100,"updated_at":"2018-01-10 04:08:30","created_at":"2018-01-10 04:08:30","id":13}

[2018-01-10 04:12:03] local.INFO: Item Updated Event Fire: {"id":1,"name":"test 3","price":100,"created_at":"2017-12-06 06:56:57","updated_at":"2018-01-10 04:12:03"}

[2018-01-10 04:13:25] local.INFO: Item Deleted Event Fire: {"id":1,"name":"test 3","price":100,"created_at":"2017-12-06 06:56:57","updated_at":"2018-01-10 04:12:03"}

I hope you found your best.... :)