Observers and Model Events Tutorial in Laravel 11
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
class PostController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
$post = Post::find(2);
return $post;
}
/**
* Show the form for creating a new resource.
*/
public function create()
{
$post_title = "This is another testing";
Post::create([
"title" => $post_title,
"description" => "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum",
"user_id" => 4
]);
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*/
public function show(string $id)
{
//
}
/**
* Show the form for editing the specified resource.
*/
public function edit(string $id)
{
//
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, string $id)
{
//
}
/**
* Remove the specified resource from storage.
*/
public function destroy(string $id)
{
//
}
}
Above File is app\Http\Controllers\PostController FileBelow File is app\Http\Controllers\UserController File
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
$user = User::with("post")->find(2);
return $user;
}
/**
* Show the form for creating a new resource.
*/
public function create()
{
$user = User::find(3)->delete();
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*/
public function show(string $id)
{
//
}
/**
* Show the form for editing the specified resource.
*/
public function edit(string $id)
{
//
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, string $id)
{
//
}
/**
* Remove the specified resource from storage.
*/
public function destroy(string $id)
{
//
}
}
Below File is app\Models\Post File
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public $timestamps = true;
protected $table = "posts";
protected $fillable = ["title", "slug", "description", "counter", "user_id"];
}
Below File is app\Models\User File
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public $timestamps = false;
protected $table = "users";
protected $fillable = ["name", "email"];
public function post()
{
return $this->hasMany(Post::class);
}
// protected static function booted(): void
// {
// static::deleted(function ($user) {
// $user->post()->delete();
// });
// static::created(function ($user) {});
// static::updated(function ($user) {});
// }
}
Below File is app\Observers\PostObserver File
<?php
namespace App\Observers;
use App\Models\Post;
use Illuminate\Support\Str;
class PostObserver
{
public function retrieved(Post $post): void
{
$post->increment("counter");
}
/**
* Handle the Post "created" event.
*/
public function created(Post $post): void
{
//
}
public function saving(Post $post): void
{
$post->slug = Str::slug($post->title, "-");
}
/**
* Handle the Post "updated" event.
*/
public function updated(Post $post): void
{
//
}
/**
* Handle the Post "deleted" event.
*/
public function deleted(Post $post): void
{
//
}
/**
* Handle the Post "restored" event.
*/
public function restored(Post $post): void
{
//
}
/**
* Handle the Post "force deleted" event.
*/
public function forceDeleted(Post $post): void
{
//
}
}
Below File is app\Observers\UserObserver File
<?php
namespace App\Observers;
use App\Models\User;
class UserObserver
{
/**
* Handle the User "created" event.
*/
public function created(User $user): void
{
//
}
/**
* Handle the User "updated" event.
*/
public function updated(User $user): void
{
//
}
/**
* Handle the User "deleted" event.
*/
public function deleted(User $user): void
{
$user->post()->delete();
}
/**
* Handle the User "restored" event.
*/
public function restored(User $user): void
{
//
}
/**
* Handle the User "force deleted" event.
*/
public function forceDeleted(User $user): void
{
//
}
}
Below File is app\Providers\AppServiceProvider File
<?php
namespace App\Providers;
use App\Models\Post;
use App\Models\User;
use App\Observers\PostObserver;
use App\Observers\UserObserver;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
User::observe(UserObserver::class);
Post::observe(PostObserver::class);
}
}
Below File is database\json\posts File
[
{
"title": "News Title One",
"slug": "news-title-one",
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
"user_id": 1
},
{
"title": "News Title Two",
"slug": "news-title-two",
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
"user_id": 2
},
{
"title": "News Title Three",
"slug": "news-title-three",
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
"user_id": 1
},
{
"title": "News Title Four",
"slug": "news-title-four",
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
"user_id": 3
},
{
"title": "News Title Five",
"slug": "news-title-five",
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
"user_id": 3
},
{
"title": "News Title Six",
"slug": "news-title-six",
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
"user_id": 1
},
{
"title": "News Title Seven",
"slug": "news-title-seven",
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
"user_id": 3
},
{
"title": "News Title Eight",
"slug": "news-title-eight",
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
"user_id": 2
}
]
Below File is database\json\users File
[
{
"name": "Yahoo Baba",
"email": "yahoobaba@gmail.com"
},
{
"name": "Salman Khan",
"email": "salman@gmail.com"
},
{
"name": "Deepika Padukone",
"email": "deepika@gmail.com"
},
{
"name": "Abhishek Bachchan",
"email": "abhishek@gmail.com"
}
]
Below File is database\migrations\2024_12_18_045236_create_users_table File
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string("name");
$table->string("email", 50)->unique();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('users');
}
};
Below File is database\migrations\2024_12_18_045425_create_posts_table File
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string("title", 50);
$table->string("slug", 100);
$table->longText("description");
$table->integer("counter")->default(0);
$table->unsignedBigInteger("user_id");
$table->foreign("user_id")->references("id")->on("users")->onUpdate("cascade")->onDelete("cascade");
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('posts');
}
};
Below File is database\seeders\DatabaseSeeder File
<?php
namespace Database\Seeders;
use App\Models\User;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*/
public function run(): void
{
// User::factory(10)->create();
// User::factory()->create([
// 'name' => 'Test User',
// 'email' => 'test@example.com',
// ]);
$this->call([
UserSeeder::class,
PostSeeder::class
]);
}
}
Below File is database\seeders\PostSeeder File
<?php
namespace Database\Seeders;
use App\Models\Post;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\File;
class PostSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
$json = File::get(path: "database/json/posts.json");
$posts = collect(json_decode($json));
$posts->each(function ($post) {
Post::create([
"title" => $post->title,
"slug" => $post->slug,
"description" => $post->description,
"user_id" => $post->user_id
]);
});
}
}
Below File is database\seeders\UserSeeder File
<?php
namespace Database\Seeders;
use App\Models\User;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\File;
class UserSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
$json = File::get(path: "database/json/users.json");
$users = collect(json_decode($json));
$users->each(function ($user) {
User::create([
"name" => $user->name,
"email" => $user->email
]);
});
}
}
Below File is routes\web File
.png)
.png)
.png)
.png)
.png)
.png)
.png)
Comments
Post a Comment