Eloquent not allowing fields starting with an unde

2019-08-04 10:27发布

Eloquent explicitly rejects fields/columns starting with an underscore

https://github.com/laravel/framework/blob/7212b1e9620c36bf806e444f6931cf5f379c68ff/src/Illuminate/Database/Eloquent/Concerns/GuardsAttributes.php#L154

It was introduced here

https://github.com/laravel/framework/commit/1000e2dca7f42d5cd5e03cbdc85fcf957b7a5548

It seems the only way around this is to manually specify each underscore column as fillable or set unguarded to be true.

Is there any reason for this ? Only reasons I can think would be a system where prefixing _ means a private variable and not put in the to DB ? Seems odd when underscore is a valid column prefix in SQL

1条回答
爷的心禁止访问
2楼-- · 2019-08-04 10:52

I think it is because Eloquent uses magic. As it does, it must enforce conventions on naming to ensure no unnecessary bugs appear.

For instance, take a look at the code of Eloquent\Model\Concerns\HasAttributes and you will see it using Str::studly to define mutators.

If Eloquent allows defining foo_column and a _foo_column, both will have the same mutators functions getFooColumn. This can lead to many problems. For example, defining a mutator for foo_column will shadow _foo_column also.

查看更多
登录 后发表回答