Skip to content

Commit

Permalink
docs: explain usage of package in README
Browse files Browse the repository at this point in the history
Relates to #1
  • Loading branch information
geoffreyvanwyk committed Aug 7, 2024
1 parent ea8c7c1 commit 72e1d9a
Showing 1 changed file with 37 additions and 3 deletions.
40 changes: 37 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@

# Observer for validating Eloquent Model

An observer that validates an Eloquent model instance before it is persisted to the database.
An observer that validates an Eloquent model instance before it is persisted to
the database, by raising a `ValidationException`.

## Install

Expand All @@ -19,8 +20,41 @@ composer require spoorsny/laravel-model-validating-observer

## Usage

> [!NOTE]
> Explain how to use the package.
Add the `ObservedBy` attribute to your model, with
`ModelValidatingObserver::class` as its argument.

Add a public, static method to your model, named `validationRules()` that
returns an associative array with the validation rules and custom messages for
your model's attributes.

```php
use Illuminate\Database\Eloquent\Attributes\ObservedBy;
use Illuminate\Database\Eloquent\Model;

use Spoorsny\Laravel\Observers\ModelValidatingObserver;

#[ObservedBy(ModelValidatingObserver::class)]
class Car extends Model
{
public static function validationRules(): array
{
return [
'rules' => [
'make' => 'required|string',
'model' => 'required|string',
],
'messages' => [
'make.required' => 'We need to know the make of the car.',
],
];
}
}
```

The observer will check each instance of your model against the validation
rules during the `saving` event triggered by Eloquent. If validation fails, a
`\Illuminate\Validation\ValidationException` will be thrown, preventing the
persistence of the invalid model instance.

## Contributing

Expand Down

0 comments on commit 72e1d9a

Please sign in to comment.