A Quick Intro To Eloquent Observers

RMAG news

Laravel’s Eloquent Observers are powerful tools that allow you to attach actions to model events that occur throughout your app. These events include creating, updating, deleting, and more, providing a convenient way to respond to changes in your application’s data without having to scatter code all over your app’s codebase.

Implementing observers involves creating a dedicated class for each model, usually within the app/Observers directory, and defining methods that correspond to the desired model events. This separation of concerns enhances code readability and makes it easier to manage application logic, especially as it grows in complexity.

Here is a list of all the Laravel model events you can listen for, utilizing Post as our example model:

namespace AppObservers;

use AppModelsPost;

class PostObserver
{
public function retrieved(Post $post): void
{
// Logic to be executed just after a Post is retrieved from the DB
}

public function creating(Post $post): void
{
// Logic to be executed just before creating a new Post is being created for the first time
}

public function created(Post $post): void
{
// Logic to be executed after creating a new Post is created for the first time
}

public function updating(Post $post): void
{
// Logic to be executed just before updating a Post
}

public function updated(Post $post): void
{
// Logic to be executed after updating a Post
}

public function saving(Post $post): void
{
// Logic to be executed just before saving a Post (fires for both create and update)
}

public function saved(Post $post): void
{
// Logic to be executed after saving a Post (fires for both create and update)
}

public function deleting(Post $post): void
{
// Logic to be executed just before deleting a Post
}

public function deleted(Post $post): void
{
// Logic to be executed after deleting a Post
}

public function forceDeleting(Post $post): void
{
// Logic to be executed before force deleting a Post
}

public function forceDeleted(Post $post): void
{
// Logic to be executed after force deleting a Post
}

public function restoring(Post $post): void
{
// Logic to be executed just before restoring a soft-deleted Post
}

public function restored(Post $post): void
{
// Logic to be executed after restoring a soft-deleted Post
}

public function replicating(Post $post): void
{
// Logic to be executed after replicating a Post
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *