Laravel Events Create Model Tutorial

Laravel 6 , Laravel , Laravel 7

Nicesnippets

2430

26-08-2020


Laravel Events Create Model Tutorial

Hi Guys,

In this example,I will learn you how to use create events for created,updated and deleted model task in laravel 7.you can easy and simply use create events for created/updated/deleted model task in laravel 7.

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.

Step 1: Create Item Table


First thing is we have to create "items". so we have to create migration for items table using Laravel 7 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\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

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;

class Item extends Model

{

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

public static function boot() {

parent::boot();

static::created(function($item) {

\Log::info('Item Created Event:'.$item);

});

static::updated(function($item) {

\Log::info('Item updated Event:'.$item);

});

static::deleted(function($item) {

\Log::info('Item Deleted Event:'.$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 5', 'price'=>100]);

dd('Item created successfully.');

});

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

\App\Item::find(50)->update(['name'=>'test 8', 'price'=>200]);

dd('Item updated successfully.');

});

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

\App\Item::find(50)->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

[2020-08-26 06:52:29] local.INFO: Item Created Event:{"name":"test 5","price":100,"updated_at":"2020-08-26T06:52:29.000000Z","created_at":"2020-08-26T06:52:29.000000Z","id":50}

[2020-08-26 06:52:55] local.INFO: Item updated Event:{"id":50,"name":"test 8","price":200,"created_at":"2020-08-26T06:52:29.000000Z","updated_at":"2020-08-26T06:52:55.000000Z"}

[2020-08-26 06:53:02] local.INFO: Item Deleted Event:{"id":50,"name":"test 8","price":"200","created_at":"2020-08-26T06:52:29.000000Z","updated_at":"2020-08-26T06:52:55.000000Z"}

It will help you...


Recommended Posts