Laravel 10 Model Observers Example Tutorial

10-Apr-2023

.

Admin

Laravel 10 Model Observers Example Tutorial

Hi Dev,

Here, Today in this article we are going to share how to work laravel 10 model observers example. this example will help you how to use laravel 10 model observers. I would like to show you what are observers in laravel 10. This tutorial will give you a simple example of laravel 10 model observers. Here, Creating a basic example of laravel 10 events and observers.

Laravel Observers will listener events for a model eloquent method like create, save, update, and delete.

I will give you a very simple definition and use of laravel observers, when you need to generate a slug or auto-generate a unique id or something like logic add before or after creating a record then observers will help you. Let’s see the Laravel Model Observers Tutorial Example step by step below.

Step 1: Download Laravel


Let us begin the tutorial by installing a new laravel application. if you have already created the project, then skip the following step.

composer create-project laravel/laravel example-app

Eloquent Hook:

  • Retrieved: after a record has been retrieved.
  • Creating: before a record has been created.
  • Created: after a record has been created.
  • Updating: before a record is updated.
  • Updated: after a record has been updated.
  • Saving: before a record is saved (either created or updated).
  • Saved: after a record has been saved (either created or updated).
  • Deleting: before a record is deleted or soft-deleted.
  • Deleted: after a record has been deleted or soft-deleted.
  • Restoring: before a soft-deleted record is going to be restored.
  • Restored: after a soft-deleted record has been restored.

Example:

Now here we will see simple example, I have one product model and it has a name, slug, price, and unique_id column. so I need to create one record with the name and price only. but when it creates I need to generate a slug from the name and auto-generate unique_id.

so let's see how to create an observers class and how it will work:

app/Models/Product.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Database\Eloquent\Model;

class Product extends Model

{

use HasFactory;

protected $fillable = [

'name', 'price', 'slug', 'unique_id'

];

}

Create observers class for Product. So, create bellow command:

php artisan make:observer ProductObserver --model=Product

app/Observers/ProductObserver.php

<?php

namespace App\Observers;

use App\Models\Product;

class ProductObserver

{

/**

* Handle the Product "created" event.

*

* @param \App\Models\Product $product

* @return void

*/

public function creating(Product $product)

{

$product->slug = \Str::slug($product->name);

}

/**

* Handle the Product "created" event.

*

* @param \App\Models\Product $product

* @return void

*/

public function created(Product $product)

{

$product->unique_id = 'PR-'.$product->id;

$product->save();

}

/**

* Handle the Product "updated" event.

*

* @param \App\Models\Product $product

* @return void

*/

public function updated(Product $product)

{

//

}

/**

* Handle the Product "deleted" event.

*

* @param \App\Models\Product $product

* @return void

*/

public function deleted(Product $product)

{

//

}

/**

* Handle the Product "restored" event.

*

* @param \App\Models\Product $product

* @return void

*/

public function restored(Product $product)

{

//

}

/**

* Handle the Product "force deleted" event.

*

* @param \App\Models\Product $product

* @return void

*/

public function forceDeleted(Product $product)

{

//

}

}

Register Observers class on the provider.

app/Providers/EventServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Auth\Events\Registered;

use Illuminate\Auth\Listeners\SendEmailVerificationNotification;

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

use Illuminate\Support\Facades\Event;

use App\Observers\ProductObserver;

use App\Models\Product;

class EventServiceProvider extends ServiceProvider

{

/**

* The event listener mappings for the application.

*

* @var array

*/

protected $listen = [

Registered::class => [

SendEmailVerificationNotification::class,

],

];

/**

* Register any events for your application.

*

* @return void

*/

public function boot()

{

Product::observe(ProductObserver::class);

}

}

Step 2: Add Route

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\ProductController;

/*

|--------------------------------------------------------------------------

| Web Routes

|--------------------------------------------------------------------------

|

| Here is where you can register web routes for your application. These

| routes are loaded by the RouteServiceProvider within a group which

| contains the "web" middleware group. Now create something great!

|

*/

Route::get('product', [ProductController::class, 'index']);

Step 3: Add Controller

php artisan make:controller ProductController

app/Http/Controllers/ProductController.php

<?php

namespace App\Http\Controllers;

use App\Models\Product;

use Illuminate\Http\Request;

class ProductController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index()

{

$product = Product::create([

'name' => 'Platinum 1',

'price' => 10

]);

dd($product);

}

}

Run Laravel App:

All steps have been done, now you have to type the given command and hit enter to run the laravel app:

php artisan serve

Now, you have to open a web browser, type the given URL and view the app output:

http://localhost:8000/product

it will create a record like below:

I hope it can help you...

#Laravel 10