Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving related records in laravel

I have users, and users belong to a dealership.

Upon user registration, I'm trying to save a new user, and a new dealership.

User database has a dealership_id column, which I want to be populated with the ID of the newly created dealership.

This is my current code in the UserController store method.

public function store() {     $user = new User();     $user->email = Input::get('email');     $user->password = Input::get('password');       $dealership = new Dealership();     $dealership->name = Input::get('dealership_name');      $user->push();     return "User Saved";  } 

Trying to use $user->push(); User data gets updated, but dealership is not created or updated.

like image 480
BeardedInBindary Avatar asked Apr 22 '14 19:04

BeardedInBindary


People also ask

How do I save a one to many relationship in Laravel?

You just need to pass the array of options with id, if id is present already in the database then it will update, if id is blank it will add a new record, If Id was there but not in your new array, then that record will get deleted.

What is polymorphic relation in Laravel?

A one-to-one polymorphic relationship is a situation where one model can belong to more than one type of model but on only one association. A typical example of this is featured images on a post and an avatar for a user. The only thing that changes however is how we get the associated model by using morphOne instead.

How to define relationship in Laravel?

To define a relationship, we need first to define the post() method in User model. In the post() method, we need to implement the hasOne() method that returns the result. Let's understand the one to one relationship through an example. First, we add the new column (user_id) in an existing table named as posts.


1 Answers

Eloquent's push() saves the model and its relationships, but first you have to tell what you want to be involved in the relationsship.

Since your user-model/table holds the id of the dealership, I assume that a user can belong to only one dealership, so the relationship should look like this:

User Model:

public function dealership() {   return $this->belongsTo('Dealership'); } 

Dealership Model:

public function users() {   return $this->hasMany('User'); } 

To save a User from the Dealership perspective, you do this:

$dealership->users()->save($user); 

To associate a dealership with a user, you do this:

$user->dealership()->associate($dealership); $user->save(); 
like image 116
Quasdunk Avatar answered Sep 20 '22 16:09

Quasdunk