- PHP >= 7.2.5
- Laravel 7|8
Please see the changelog for more information on what has changed recently.
Include the following in your composer.json
"repositories": [
{
"type": "vcs",
"url": "https://github.com/JeffersonLab/laravel-utilities.git"
}
],
"require" : {
"jlab/laravel-utilities" : "^8.0"
}
Then
"composer update jlab/laravel-utilities"
$ composer update
$ vendor/bin/phpunit
The following validation rules are provided
InConfig
The field under validation must be a member of the named configuration parameter. The configuration parameter may be specified using laravel's dot-array notation. Multi-level arrays will be searched as flat arrays for validation purposes.
Examples
// The app.php config contains
// 'status_codes' = ['foo','bar'],
//The validation rule can be accessed via string short-hand
$rules = [
'inputStatusCode' => 'inConfig:app.status_codes'
];
//or via the underlying InConfig rule class
$rules = [
'inputStatusCode' => new InConfig('app.status_codes'),
];
Create a class that extends BaseModel and then place any desired validation rules into $rules.
class MyModel extends BaseModel
{
public static $rules = [
'username' => 'required | max:8',
];
}
Calls to save() will return false if the model attributes do not validate successfully against $rules. The errors() method will return a laravel MessageBag containing validation error messages:
$model = new MyModel(['username'=>'longerthan8chars']);
$model->save(); // false
$model->hasErrors(); // true
print_r($model->errors()->toArray(); // show the errors
If necessary, there are two ways to save the model regardless of whether it validates or not.
The first is by setting mustValidate to false. In this scenario the validation still occurs, but does not prevent save from proceeding if possible.
$model = new MyModel(['username'=>'longerthan8chars']);
$mode->mustValidate = false;
$model->save(); // true
$model->hasErrors(); // true
print_r($model->errors()->toArray(); // show the errors
The second is by calling quickSave()
$model = new MyModel(['username'=>'longerthan8chars']);
$model->quickSave(); // true
$model->hasErrors(); // false only b/c we didn't check!
Of course when bypassing validation checks, there is even more onus is on the user to handle outcomes such as database exceptions that might be caused by trying to save bad data.
BaseModel adds validating and validated events to supplement the existing created, creating, saved, saving, etc. events available on standared Eloquent models
Returning false from the listener of validating will cancel validation. The validated event is only dispatched following a successful validation.
Contributions are neither sought nor desired at this time.