May eloquently ignore irrelevant data in Laravel 4

I have a form that accepts data that will be used to create two new database table records. The form accepts both user data and their address. User data will be saved using the User::create(Input::all()) method in the users table, and address data will be saved using the Address::create(Input::all()) method in the database address table.

The problem that I am currently facing is that Eloquent complains that the street, city, country, etc. does not exist in the user table. It is true that data should be used for the address side of things.

Is there a way to eloquently ignore irrelevant data in the Input::all() array when passing to creation methods?

Ps I know mass assignment is not a good idea, I use it here to simplify my question.

0
source share
4 answers

Of course, you can use the $fillable in your model to declare fields allowed for mass assignment. I think this is the most suitable solution in your case.

 class User extends Eloquent { protected $fillable = [ 'first_name', 'last_name', 'email' ]; } 
+3
source

Have you tried watching 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

+2
source

You will have to disable this model using these http://laravel.com/docs/eloquent#mass-assignment , and then manually disable these values โ€‹โ€‹before executing save() . I highly recommend using a form object or something similar to complete this kind of service outside of your model, as it is safer and usually more clear for the intended behavior.

0
source

@cheelahim correctly, when passing an array to Model :: create (), all additional values โ€‹โ€‹that are not in Model :: fillable will be ignored.

I would, however, STRONGLY RECOMMEND that you do not pass Input :: all () to the model. You really need to validate and verify the data before throwing it into the model.

0
source

All Articles