Observe (and react to) attribute changes made on Eloquent models.

Overview

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

You might also like...
Use auto generated UUID slugs to identify and retrieve your Eloquent models.

Laravel Eloquent UUID slug Summary About Features Requirements Installation Examples Compatibility table Alternatives Tests About By default, when get

Record created by, updated by and deleted by on Eloquent models automatically.

quarks/laravel-auditors Record created by, updated by and deleted by (if SoftDeletes added) on Eloquent models automatically. Installation composer re

Eloquent Befriended brings social media-like features like following, blocking and filtering content based on following or blocked models.
Eloquent Befriended brings social media-like features like following, blocking and filtering content based on following or blocked models.

Laravel Befriended Eloquent Befriended brings social media-like features like following, blocking and filtering content based on following or blocked

An Eloquent Way To Filter Laravel Models And Their Relationships

Eloquent Filter An Eloquent way to filter Eloquent Models and their relationships Introduction Lets say we want to return a list of users filtered by

๐Ÿ•ต๏ธ Inspect Laravel Eloquent models to collect properties, relationships and more.

๐Ÿ•ต๏ธ Eloquent Inspector Inspect Laravel Eloquent models to collect properties, relationships and more. Install Via Composer composer require cerbero/el

Laravel Nova Ban simplify blocking and banning Eloquent models.
Laravel Nova Ban simplify blocking and banning Eloquent models.

Laravel Nova Ban Introduction Behind the scenes cybercog/laravel-ban is used. Contents Installation Usage Prepare bannable model Prepare bannable mode

Package with small support traits and classes for the Laravel Eloquent models

Contains a set of traits for the eloquent model. In future can contain more set of classes/traits for the eloquent database.

๐Ÿ Web application made in PHP with Laravel where you can interact via API with my Snake game which is made in Python
๐Ÿ Web application made in PHP with Laravel where you can interact via API with my Snake game which is made in Python

Snake web application Project of the web application where you can interact via API with Snake game which is available to download on it. Application

Easy creation of slugs for your Eloquent models in Laravel

Eloquent-Sluggable Easy creation of slugs for your Eloquent models in Laravel. NOTE: These instructions are for the latest version of Laravel. If you

Comments
  • if ($model->wasChanged()) { return false on created

    if ($model->wasChanged()) { return false on created

    When listening for created events, which is possible according to the documentation, the check $model->wasChanged() returns false. It should be replaced with $model->isDirty();

    question 
    opened by ronnievisser 3
  • Update code style

    Update code style

    Hey there, thanks for the repository! I wanted to do a small code style change to the LaravelAttributeObserverServiceProvider to increase it's readability and with that it's maintainability. This is done with the use of guard clauses to reduce the cyclomatic complexity. In simple terms, it makes sure you don't have to indent the code as much.

    You are welcome to disagree with my changes though. I'm looking forward to your reply. :)

    opened by RobinBastiaan 0
Releases(1.4.0)
  • 1.4.0(Jan 1, 2023)

    • Ensure badges conform with badges/shields #8671
    • Updated dependencies

    Full Changelog: https://github.com/alexstewartja/laravel-attribute-observer/compare/1.3.1...1.4.0

    Source code(tar.gz)
    Source code(zip)
  • 1.3.1(Sep 28, 2022)

  • 1.3.0(Jun 19, 2022)

    What's Changed

    • Fix for Laravel 9 by @neopheus in https://github.com/alexstewartja/laravel-attribute-observer/pull/3

    New Contributors

    • @neopheus made their first contribution in https://github.com/alexstewartja/laravel-attribute-observer/pull/3

    Full Changelog: https://github.com/alexstewartja/laravel-attribute-observer/compare/1.2.1...1.3.0

    Source code(tar.gz)
    Source code(zip)
  • 1.2.1(Dec 2, 2021)

    What's Changed

    • Update code style by @RobinBastiaan in https://github.com/alexstewartja/laravel-attribute-observer/pull/1
    • Added Artisan command tests

    New Contributors

    • @RobinBastiaan made their first contribution in https://github.com/alexstewartja/laravel-attribute-observer/pull/1

    Full Changelog: https://github.com/alexstewartja/laravel-attribute-observer/compare/1.0.4...1.2.1

    Source code(tar.gz)
    Source code(zip)
  • 1.0.4(Oct 9, 2021)

  • 1.0.3(Oct 1, 2021)

  • 1.0.2(Oct 1, 2021)

  • 1.0.1(Sep 30, 2021)

Owner
Alex Stewart
Alex Stewart
cybercog 996 Dec 28, 2022
Generate UUID for a Laravel Eloquent model attribute

Generate a UUIDv4 for the primary key or any other attribute on an Eloquent model.

Alex Bouma 4 Mar 1, 2022
This is a simple url bot validator made with laravel and react

?? This is a simple URL validator. Used Technologies React - Javascript framework Laravel - PHP framework Mysql - Relational database Installation Ins

Vanderson Telema 1 Oct 27, 2021
PHP 8 attribute to register Laravel model observers.

PHP 8 attribute to register Laravel model observers. Instead of defining observers inside service providers this package offers an alternative way to

gpanos 15 May 30, 2022
The idea of this package is using PHP Attribute in a laravel project

Laravel #[Annotation] Introduction PHP 8.0 release was a revolution for the language. It brings cool features like Named arguments, Attributes, Constr

null 13 Apr 29, 2022
Is an Extension of Laravel View Class which compiles String Template on the fly. It automatically detects changes on your string template and recompiles it if needed.

Laravel-fly-view Is an Extension of Laravel View Class which compiles String Template on the fly. It automatically detects changes on your string temp

John Turingan 16 Jul 17, 2022
Automatic multi-tenancy for Laravel. No code changes needed.

Tenancy for Laravel โ€” stancl/tenancy Automatic multi-tenancy for your Laravel app. You won't have to change a thing in your application's code. โœ”๏ธ No

Samuel ล tancl 2.7k Jan 3, 2023
Watch your Laravel app for unwanted changes when working with third-party packages.

Project Secure This package installs a Composer plugin that reports unwanted changes to your Laravel project code after installing or updating a third

The Laravel Hacker 3 Nov 3, 2021
An Eloquent Way To Filter Laravel Models And Their Relationships

Eloquent Filter An Eloquent way to filter Eloquent Models and their relationships Introduction Lets say we want to return a list of users filtered by

Eric Tucker 1.5k Jan 7, 2023
Laravel Ban simplify blocking and banning Eloquent models.

Laravel Ban Introduction Laravel Ban simplify management of Eloquent model's ban. Make any model bannable in a minutes! Use case is not limited to Use

cybercog 879 Dec 30, 2022