Best laravel framework open-source packages.

Laravel attribute observer

Observe (and react to) attribute changes made on Eloquent models.
Updated 3 months ago

Laravel Attribute Observer

Laravel Attribute Observer - Social Image

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

Donate Buy Me A Coffee

Requirements

  • PHP: 7.4+
  • Laravel: 7+

Installation

You can install the package via composer:

composer require alexstewartja/laravel-attribute-observer

Configuration

Publish the config file (config/attribute-observer.php) with:

php artisan vendor:publish --provider="AlexStewartJA\LaravelAttributeObserver\LaravelAttributeObserverServiceProvider"

This is the default content of the published config file:

return [
    /*
    |--------------------------------------------------------------------------
    | Attribute Observers
    |--------------------------------------------------------------------------
    |
    | Here you may configure all desired Models and their respective Attribute
    | Observers. For example:
    |
    | 'observers' => [
    |    \App\Models\Order::class => [
    |        \App\AttributeObservers\OrderStatusObserver::class,
    |    ],
    | ]
    |
    */

    'observers' => [
        // Define your model & attribute observers here...
    ]
];

Populate the observers array with your desired Model => Attribute Observer mappings.

Usage

Attribute Observers

The make:laravel-attribute-observer Artisan command is the easiest way to create a new attribute observer class:

php artisan make:laravel-attribute-observer OrderStatusObserver --model=Order

This command will place the new attribute observer in your App/AttributeObservers directory. If this directory does not exist, Artisan will create it for you. Your freshly generated attribute observer will look like the following:

<?php

namespace App\AttributeObservers;

use App\Models\Order;

class OrderStatusObserver
{
    /**
     * Handle changes to the "id" field of Order on "created" events.
     *
     * @param \App\Models\Order $order
     * @param mixed $newValue The current value of the field
     * @param mixed $oldValue The previous value of the field
     * @return void
     */
    public function onIdCreated(Order $order, mixed $newValue, mixed $oldValue)
    {
        //
    }
}

You may then modify the code to match your business logic, for example:

<?php

namespace App\AttributeObservers;

use App\Events\OrderStatusChanged;
use App\Models\Order;

class OrderStatusObserver
{
    /**
     * Handle changes to the "status" field of Order on "saved" events.
     *
     * @param \App\Models\Order $order
     * @param mixed $newValue The current value of the field
     * @param mixed $oldValue The previous value of the field
     * @return void
     */
    public function onStatusSaved(Order $order, mixed $newValue, mixed $oldValue)
    {
        // Dispatch an event that sends an order update email to the customer
        OrderStatusChanged::dispatch($order);
    }
}

Attribute Observer methods are always supplied with the model instance, the new attribute value and the previous attribute value, in that order.

Events

You may observe all the typical CRUD events dispatched by Eloquent models during their lifecycles. Supported events are: creating, created, updating, updated, saving, saved, deleting, deleted.

The naming convention to follow when defining attribute observer methods is: on|AttributeName|Event

So, let's say we want to check a user's email against a global spam/vanity mail list each time they attempt to update it, we would implement that logic in an attribute observer method called onEmailUpdating.

Note that the attribute name must be in PascalCase and the event name must be Capitalized.

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

Donations

I maintain this package in my spare time. If it's beneficial to you, consider donating or buying me a coffee to keep it improving.

Donate Buy Me A Coffee