Lucid: Fillable and guarded properties is supported?

Created on 14 Feb 2017  路  7Comments  路  Source: adonisjs/lucid

Most helpful comment

I've taken to use a static get inside my models and then do something like this:

User.create(request.only(User.fillable))

this way I only need to update the getter instead of each array every time a field is added to the model, It would be nice if this was supported from the framework side

All 7 comments

Hey @enniel !

No they are not !

It was not implemented because using request.all() is bad practice. You need to specify which field you want from the request directly request.only('email', 'password').

@RomainLanz It makes sense. Thanks!

Little correction:
request.only(['email', 'password'])
instead
request.only('email', 'password')

@RomainLanz - i don't see how picking from the request is any better than filtering via a fillable array. I think it's actually a worse practice. You're just changing the location of where the filtering is occurring (at the point of the request vs at the point of the fill).

I think filtering at a model level is the better practice because there may be other data sources aside from the request that are passed through to the model and assigning fillable at the model level means regardless of the source of the data it is still getting correctly filtered. Additionally, even if you're only pulling from the request, there may be multiple places where you need to do this and it's alot simpler to just have this logic handled at a model level.

Hey @mattcdavis1! 馃憢

I'm taking this in consideration for next release. 馃憤

I've taken to use a static get inside my models and then do something like this:

User.create(request.only(User.fillable))

this way I only need to update the getter instead of each array every time a field is added to the model, It would be nice if this was supported from the framework side

I wrote this one quickly that could probably be evolved on.

    // Override merge to allow for fillable intersection
    merge(attributes = {})
    {
        attributes = Object
            .entries(attributes)
            .filter(x => this.constructor.fillable.indexOf(x[0]) > -1)
            .reduce((x, [key, val]) => {
                x[key] = val;
                return x;
            }, {});

        return super.merge(attributes);
    }

To be used like: (extended for demo purposes)

```
class User extends ...
{
/**
* @type {string}
*/
static get fillable() {
return [
'email',
'name',
];
}
}

--

// {
// name: 'Your name',
// email: '[email protected]',
// badData: 'to be excluded'
// }
const data = request.all();

// Merge with intersection
const model = new User;
model.merge(data);

// { email: '[email protected]', name: 'Your Name' }
console.log( model.toJSON() );

Was this page helpful?
0 / 5 - 0 ratings