In this tutorial you will learn about the Laravel 8 Model Observers Tutorial Example and its application with practical example.
In this Laravel 8 Model Observers Tutorial Example tutorial I will show you how model observers works and how to use model observers in larave 8. In this tutorial you will learn to use model observers in laravel 8. In this article I will help you understand how to use laravel 8 model observers. I will also show you what is observers in laravel 8. I will also share simple example of laravel 8 model observers. We will also be creating basic example of events and observers in laravel 8.
Laravel Model Observers
When you want to listen multiple events on a given model then you can use observers to group all of your listeners into a single class. Laravel Observers are simple classes with method names that reflect the Eloquent events you wish to listen for. Each of these methods receives the model as their only argument. Laravel Observers will listen event for model like create, update and delete.
In this step by step tutorial you will understand Laravel 8 Model Observers with example.
Laravel 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 orupdated).
- Saved: after a record has been saved (either created orupdated).
- 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 berestored.
- Restored: after a soft-deleted record has been restored.
Support we have a product model with name, slug, price and unique_id column. Now when I create one record with name an price only I want to generate slug from name and auto generate unique_id. Let’s see how to Model observers class will works:
app/Models/Product.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?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' ]; } |
Now, lets create observers class for Product model using following artisan command:
1 |
php artisan make:observer ProductObserver --model=Product |
app/Observers/ProductObserver.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
<?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) { } } |
Now, we need to register observers class in provider.
app/Providers/EventServiceProvider.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<?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); } } |
Create Demo Route
we need to define routes in “routes/web.php” file. Lets open “routes/web.php” file and add the following routes in it.
routes/web.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?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']); |
Create Controller:
Now, lets create a controller named ProductController using command given below –
1 |
php artisan make:controller <strong>ProductController</strong> |
Once the above command executed, it will create a controller file ProductController.php in app/Http/Controllers/ directory. Open the ProductController.php file and put the following code in it.
app/Http/Controllers/ProductController.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?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); } } |