5

I understand that in order to save a foreign key, one should use the related model and the associate() function, but is it really worth the trouble of going through this

$user = new User([
    'name' => Input::get('name'), 
    'email' => Input::get('email')
]);

$language = Language::find(Input::get('language_id');
$gender = Gender::find(Input::get('gender_id');
$city = City::find(Input::get('city_id');

$user->language()->associate($language);
$user->gender()->associate($gender);
$user->city()->associate($city);

$user->save();

when one can simply do this?

User::create(Input::all());

I feel like I'm missing something here, maybe there's an even simpler and cleaner way to handle foreign keys in controllers (and views)?

Archy Will He 何魏奇
  • 9,589
  • 4
  • 34
  • 50
Nicolas
  • 2,754
  • 6
  • 26
  • 41

2 Answers2

1

You can use push() method instead which would allow you to push to related models.

This link should answer your query. Eloquent push() and save() difference

Community
  • 1
  • 1
Yashaswini
  • 49
  • 5
0

I really don't see anything wrong at all with doing User::create(Input::all());.

Obviously you'd want some validation, but it's doing the same thing.

I think the associate() method is more useful for the inverse of your situation.

For example, say you had a form which a user could fill out to add their city to your app, and upon doing so, they should automatically be assigned to that city.

$city = City::create(Input::all()); would only achieve the first half of your requirements because the user has not yet been attached as city does not have a user_id column.

You'd then need to do something like $city->user()->associate(User::find(Auth::user()->id));

user1669496
  • 32,176
  • 9
  • 73
  • 65
  • Thanks for your input, of course there's validation required but that's for both cases so I didn't put it on purpose. Maybe you're right, in your scenario associate() has more meaning, but I guess I haven't done enough with L4 yet to know when `associate()` will come in handy. I'm willing to let this question open to see if somebody comes with a better explanation/idea though. Cheers – Nicolas Mar 06 '14 at 13:57