How To Work with Laravel 10 Model Events Tutorial

Reading Time: 8 minutes
739 Views

Inside this article we will see the concept i.e How To Work with Laravel 10 Model Events Tutorial. Article contains the classified information i.e Laravel 10 Model Events: A Comprehensive Guide.

Laravel 10 Model Events are an essential feature of the Laravel PHP framework that allows developers to define and handle events that occur during the lifecycle of a model.

These events can be triggered by actions such as creating, updating, deleting, or restoring a model, and can be used to automate tasks, perform validations, or integrate with third-party services.

Read More: Laravel 10 How To Connect with Multiple Database Tutorial

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

What are Model Events in Laravel?

A Model in Laravel 10 provides an abstraction for working with a database table with a high-level API. Among these APIs, events are which are fired when actions are performed on the model.

Models events in simple terms are hooks of a model’s life cycle which you can use to easily run code when database records are saved, updated or deleted.

Events receive the instance of the model which is being saved, updated or deleted.

Here are the following events which we can use with laravel model –

  • creating and created: Fires before and after records have been created.
  • updating and updated: Fires before and after records are updated.
  • saving and saved: Fires before and after records are saved (i.e created or updated).
  • deleting and deleted: Fires before and after records are deleted or soft-deleted.
  • restoring and restored: Fires before and after soft-deleted records are restored.
  • retrieved: Fires after records have been retrieved.

Working with Model Events

Suppose, we have a CRUD application for devices in which we are performing –

  • Create & Save device data into database table
  • Update Device data
  • List Device rows
  • Delete device data

Here, the code for Device.php (Model file)

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Device extends Model
{
    use HasFactory;

    protected $fillable = [
        "name", 
        "status"
    ];
}

Read More: Laravel 10 Generate PDF and Attach To GMail Email Tutorial

Controller file – DeviceController.php

<?php

namespace App\Http\Controllers;

use App\Models\Device;
use Illuminate\Http\Request;

class DeviceController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $all_devices = Device::all();

        return view("crud.index", [
            "devices" => $all_devices
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view("crud.create");
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $device = new Device();

        $device->name = $request->name;
        $device->status = $request->status;

        $device->save();

        $request->session()->flash("success", "Device created successfully");

        return redirect("device");
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Device  $device
     * @return \Illuminate\Http\Response
     */
    public function show(Device $device)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Device  $device
     * @return \Illuminate\Http\Response
     */
    public function edit(Device $device)
    {
        return view("crud.edit", [
            "device" => $device
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Device  $device
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $device = Device::find($id);

        $device->name = $request->name;

        $device->status = $request->status;

        $device->save();

        $request->session()->flash("success", "Data updated successfully");

        return redirect("device");
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Device  $device
     * @return \Illuminate\Http\Response
     */
    public function destroy(Device $device)
    {
        $device->delete();

        return redirect()->route("device.index")->with("success", "Device deleted successfuly");
    }
}

Create Read Update Delete

Create & Save Operation

public function store(Request $request)
{
    //...
}

Update Operation

public function update(Request $request, $id)
{
    //...
}

Delete Operation

public function destroy(Device $device)
{
    //...
}

Here, we have taken a CRUD sample application.

Read More: Step-by-Step JSON Data Seeding with Laravel 10 Tutorial

Now,

We will create model events and attach with this CRUD application.

How To Create Model Events

Model events trigger when model perform any operational function.

Open model file, Device.php. Add events into it.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;

class Device extends Model
{
    use HasFactory;

    protected $fillable = [
        "name", 
        "status"
    ];

    // Define model events and Point of execution
    public static function boot() {
  
        parent::boot();
  
        /**
         * Write code on Method
         *
         * @return response()
         */
        static::creating(function($item) { 
          
            Log::info('Creating event call: '.$item); 
        });
  
        /** 
         * Write code on Method
         *
         * @return response()
         */
        static::created(function($item) {           
            /*
                Write Logic Here
            */ 
  
            Log::info('Created event call: '.$item);
        });
  
        /**
         * Write code on Method
         *
         * @return response()
         */
        static::updating(function($item) { 
                       
            Log::info('Updating event call: '.$item); 
        });
  
        /**
         * Write code on Method
         *
         * @return response()
         */
        static::updated(function($item) {  
            /*
                Write Logic Here
            */    
            Log::info('Updated event call: '.$item);
        });
  
        /**
         * Write code on Method
         *
         * @return response()
         */
        static::deleted(function($item) { 

            Log::info('Deleted event call: '.$item); 
        });
    }
}

These are model events and hook point where they fire.

Before Data Create

static::creating(function($item) { ... });

After Data Save

static::created(function($item) { ... });

Before Data Update

static::updating(function($item) { ... });

After Data Update

static::updated(function($item) { ... });

After Data Delete

static::deleted(function($item) { ... });

Application Execution

When we run CRUD application, logs will be logged into /storage/logs/laravel.log file.

[2023-02-08 01:30:51] local.INFO: Creating event call: {"name":"Device 100","status":"0"}  
[2023-02-08 01:30:52] local.INFO: Created event call: {"name":"Device 100","status":"0","updated_at":"2023-02-08T01:30:51.000000Z","created_at":"2023-02-08T01:30:51.000000Z","id":4}  
[2023-02-08 01:32:37] local.INFO: Updating event call:  {"id":4,"name":"Device 100","status":"1","created_at":"2023-02-08T01:30:51.000000Z","updated_at":"2023-02-08T01:30:51.000000Z"}  
[2023-02-08 01:32:37] local.INFO: Updated event call: {"id":4,"name":"Device 100","status":"1","created_at":"2023-02-08T01:30:51.000000Z","updated_at":"2023-02-08T01:32:37.000000Z"}  
[2023-02-08 01:34:25] local.INFO: Deleted event call: {"id":2,"name":"Test Device 10","status":"1","created_at":"2021-09-11T02:33:42.000000Z","updated_at":"2021-09-11T11:56:39.000000Z"}  

Successfully, we can see the complete working concept and idea of Laravel Model Events.

Read More: Laravel 10 and Google Bar Chart Integration Tutorial

We hope this article helped you to Learn How To Work with Laravel 10 Model Events Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.