Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving a model with multiple foreign keys in Laravel 4

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)?

like image 688
Nicolas Avatar asked Nov 10 '22 11:11

Nicolas


1 Answers

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

like image 79
Yashaswini Avatar answered Nov 15 '22 12:11

Yashaswini