Can eloquent ignore irrelevant data in Laravel 4

2019-03-04 09:50发布

I have a form that accepts data which will be used to create two new database table entries. The form takes both the users details and their address. The user details will be stored using the User::create(Input::all()) method into the users table, and the address details will be stored using the Address::create(Input::all()) method into the addresses table of the database.

The issue I'm currently having is that Eloquent is complaining that street, city, country etc do not exist on the users table. This is true, that data is to be used for the address side of things.

Is there any way to have eloquent ignore irrelevant data in the Input::all() array when it's passed to the create methods?

P.s. I'm aware that mass-assignment isn't a good idea, I'm only using it here to simplify my question.

4条回答
做个烂人
2楼-- · 2019-03-04 10:05

You'll have to unguard that model using these http://laravel.com/docs/eloquent#mass-assignment and then manually unset those values before you execute save(). I highly recommend using a form object or something similar to complete this kind of service for you outside of your model since it's safer and usually clearer to intended behavior.

查看更多
等我变得足够好
3楼-- · 2019-03-04 10:08

Sure enough you can use $fillable array in your model to declare fields allowed for mass-assignment. I believe this is the most sufficient solution in your case.

class User extends Eloquent {

    protected $fillable = [
        'first_name',
        'last_name',
        'email'
    ];
}
查看更多
Emotional °昔
4楼-- · 2019-03-04 10:10

@cheelahim is correct, When passing an array to Model::create(), all extra values that aren't in Model::fillable will be ignored.

I would however, STRONGLY RECOMMEND that you do not pass Input::all() to a model. You really should be validating and verifying the data before throwing it into a model.

查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-03-04 10:18

Have you tried looking at Input::only('field1','field2',...);, or even Input::except('field3')? They should be able to accomplish what you are looking for.

Source: http://laravel.com/docs/requests

查看更多
登录 后发表回答