Showing posts with label laravel 8 observers example. Show all posts
Showing posts with label laravel 8 observers example. Show all posts

Laravel 8 Model Observers Example Tutorial

Laravel 8 Model Observers Example Tutorial

Hi Dev,

Nowdays,i will analyze you a way to use laravel 8 observers. this example will help you a way to use laravel 8 model observers. i would love to expose you what is observers in laravel 8. This tutorial will come up with simple instance of laravel eight model observers.

We can come up with very simple definition and use of laravel observers is, when you want to generate slug or auto generate precise identification or something like common sense add earlier than or after create document then observers will help you. i can come up with bellow events that provide via observers and easy instance bellow.

Here, i will give you complete instance for in reality model Observers the usage of Laravel eight 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:

Now In this blog,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
<?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
<?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
<?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
<?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
<?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' => 'Milk',
            'price' => 30
        ]);
  
        dd($food);
    }
}

Now you can run project.

It will help you...