Laravel Model Observers Tutorial Example From Scratch
First of all, you need to follow this step.
Step 1: Install laravel 8 App
Step 2: Database Configuration in .env file
Step 3: Run PHP artisan Migrate
Step 4: Create Model
Step 5: Create observers class for Product.
Step 6: Add Routes
Step 7: Creating Product Controller
Step 8: Run Development Server
Step 1: Install laravel 8 App
We need to run command to create Laravel 8 projects.
composer create-project --prefer-dist laravel/laravel laravel_observers
cd laravel_observers
Step 2: Database Configuration in .env file
Next step, we will set the database credentials in the application. Let’s open your project .env file and set the database credentials here.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Scaffolding
DB_USERNAME=root
DB_PASSWORD=root@123
This is the list of all of the events, eloquent model fired that we can hook into
- retrieved
- creating
- created
- updating
- updated
- saving
- saved
- deleting
- deleted
- restoring
- restored
Step 3: Run PHP artisan Migrate
php artisan make:migration create_products_table
Create Migration and put code below.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('price');
$table->string('slug');
$table->string('unique_id')->nullable();
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('products');
}
}
Run Migrate
php artisan migrate
Step 4: Create Model
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'
];
}
Step 5: Create observers class for Product.
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 = 'MAC-'.$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 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 6: Add Routes
In this step, Add routes in the web.php file as below.
Navigate to routes/web.php file and update the following routes:
<?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 Route:
Step 7: Creating Product Controller
In this step, create a new controller name ProductController. So use the below command and create a new controller that name is 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' => 'Mac Book',
'price' => 50000
]);
dd($product);
}
}
Step 8: Run Development Server
php artisan serve
http://127.0.0.1:8002/product
Git: https://github.com/siddharth018/Laravel-8-Model-Observers.git