I have been using laravel for a couple of times and when I used laravel 4 before, I used to add the rules for validation as a static member of the model. Like this one:
class Foo extends ValidatableModel
{
protected static $rules = [
'bar' => 'required'
];
}
The ValidatableModel extends Laravel's base Model and then has custom method to fill the attributes. I have no fillable property.
Now, in Laravel 5, I am not using this because of the further decoupling of validation which is good. With the advent of Request where you can specify the rules, I am now using the fillable property but I just don't like the duplication where you specify the field in the fillable property and then add the same field in the specific Request object. Too much work when adding/removing database fields.
I am of the mindset that a fillable property is a property that needs to be validated. Correct me if I am wrong here but so far, that has been my experience.
I have something in mind but I still have to test if it will work. Basically, I have to create my own base Model where I would set the values of fillable from a Request class. Something like below:
class FooRequest
{
public static $rules = [
'bar' => 'required'
];
}
...
class FooModel extends ValidatableModel
{
public $fillable = [];
public static function boot()
{
parent::boot();
static::creating(function($model) {
$requestClass = 'come up based on naming convention';
$rules = $requestClass::$$rules;
$model->fillable = array_keys($rules);
});
}
}
I don't know if this will work. I was just thinking about it and maybe I'll try it when I get home. And it looks like a lot of work just to eliminate the duplication in fillable property.
What do you guys think?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire