Laravel 8 Model Observers Tutorial

Laravel 8 , Laravel 7 , Laravel , Laravel 6

Nicesnippets

9976

21-04-2021


Laravel 8 Model Observers Tutorial

Hi Guys,

Today,I will learn you how to use laravel 8 observers. this example will help you how to use laravel 8 model observers. i would like to show you what is observers in laravel 8. This tutorial will give you simple example of laravel 8 model observers.

We will give you very simple definition and use of laravel observers is, when you need to generate slug or auto generate unique id or something like logic add before or after create record then observers will help you. i will give you bellow events that provide by observers and simple example bellow.

Here, I will give you full example for simply Model Observers using Laravel 8 as bellow.

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:

here In this example,we will see simple example, i have one Food model and it has name, slug, price and unique_id column. so i need to create one record with name an price only. but when it's create i need to generate slug from name and auto generate unique_id.

app/Models/Food.php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Database\Eloquent\Model;

class Food extends Model

{

use HasFactory;

protected $fillable = [

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

];

}

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

php artisan make:observer FoodObserver --model=Food

app/Observers/FoodObserver.php

namespace App\Observers;

use App\Models\Food;

class FoodObserver

{

/**

* Handle the Food "created" event.

*

* @param \App\Models\Food $food

* @return void

*/

public function creating(Food $food)

{

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

}

/**

* Handle the Food "created" event.

*

* @param \App\Models\Food $food

* @return void

*/

public function created(Food $food)

{

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

$food->save();

}

/**

* Handle the Food "updated" event.

*

* @param \App\Models\Food $food

* @return void

*/

public function updated(Food $food)

{

}

/**

* Handle the Food "deleted" event.

*

* @param \App\Models\Food $food

* @return void

*/

public function deleted(Food $food)

{

}

/**

* Handle the Food "restored" event.

*

* @param \App\Models\Food $food

* @return void

*/

public function restored(Food $food)

{

}

/**

* Handle the Food "force deleted" event.

*

* @param \App\Models\Food $food

* @return void

*/

public function forceDeleted(Food $food)

{

}

}

Register Observers class on provider.

app/Providers/EventServiceProvider.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\FoodObserver;

use App\Models\Food;

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()

{

Food::observe(FoodObserver::class);

}

}

Create Demo Route:

routes/web.php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\FoodController;

/*

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

| 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('food', [FoodController::class, 'index']);

Create Controller Route:

app/Http/Controllers/FoodController.php

namespace App\Http\Controllers;

use App\Models\Food;

use Illuminate\Http\Request;

class FoodController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index()

{

$food = Food::create([

'name' => 'WaterMelon',

'price' => 10

]);

dd($food);

}

}

Now you can run project.

It will help you...