Saving related records in laravel

BeardedInBindary picture BeardedInBindary · Apr 22, 2014 · Viewed 59k times · Source

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.

Answer

Quasdunk picture Quasdunk · Apr 22, 2014

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();