๐Ÿ‹๏ธ
Lift for Laravel
View on GitHub
  • ๐Ÿ‹๏ธLift for Laravel
  • ๐Ÿš€Getting Started
    • Installation
    • Changelog
  • ๐Ÿ› ๏ธAttributes
    • Cast
    • Column
    • Config
    • DB
    • Events
    • Fillable
    • Hidden
    • Ignore Properties
    • Immutable
    • Primary Key
    • Relationships
    • Validation
    • Watch
  • ๐ŸงชMethods
    • castAndCreate
    • castAndFill
    • castAndSet
    • castAndUpdate
    • createValidationMessages
    • createValidationRules
    • customColumns
    • defaultValues
    • immutableProperties
    • updateValidationMessages
    • updateValidationRules
    • validationMessages
    • validationRules
    • watchedProperties
  • ๐Ÿค–Commands
    • lift:migration
Powered by GitBook
On this page

Was this helpful?

  1. Attributes

Watch

By default, Eloquent already fires events when updating models, but it is a generic event. With the Watch attribute you can set a specific event to be fired when a specific public property is updated. The event will receive as a parameter the updated model instance.

use Carbon\CarbonImmutable;
use Illuminate\Database\Eloquent\Model;
use Tests\Datasets\PriceChangedEvent;
use Tests\Datasets\RandomNumberChangedEvent;
use WendellAdriel\Lift\Attributes\Cast;
use WendellAdriel\Lift\Attributes\Fillable;
use WendellAdriel\Lift\Attributes\Watch;
use WendellAdriel\Lift\Lift;

final class Product extends Model
{
    use Lift;

    #[Fillable]
    public string $name;

    #[Watch(PriceChangedEvent::class)]
    #[Fillable]
    #[Cast('float')]
    public float $price;

    #[Fillable]
    #[Cast('int')]
    public int $random_number;

    #[Fillable]
    #[Cast('immutable_datetime')]
    public CarbonImmutable $expires_at;
}
final class PriceChangedEvent
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public function __construct(
        public Product $product,
    ) {
    }
}
PreviousValidationNextcastAndCreate

Last updated 1 year ago

Was this helpful?

๐Ÿ› ๏ธ