Saving related records in laravel

LaravelLaravel 4One to-ManyEloquent

Laravel Problem Overview


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.

Laravel Solutions


Solution 1 - Laravel

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

Solution 2 - Laravel

Please check this answer to see the difference of push() and save()

You will need to define correctly your models relationships as per documentation If this is done correctly, it should work . This is what push() does :

/**
 * Save the model and all of its relationships.
 *
 * @return bool
 */

    public function push()
    {
        if ( ! $this->save()) return false;
    
        // To sync all of the relationships to the database, we will simply spin through
        // the relationships and save each model via this "push" method, which allows
        // us to recurse into all of these nested relations for the model instance.
    
        foreach ($this->relations as $models)
        {
            foreach (Collection::make($models) as $model)
            {
                if ( ! $model->push()) return false;
            }
        }
    
        return true;
    }

In your case, you have a one (dealership) belongs to many (users)

In your Users model :

class Users extends Eloquent {

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

    }

}

In the example above, Eloquent will look for a dealership_id column on the users table. In your Dealership Model :

class Dealership extends Eloquent {

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

}

In your store function :

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

Learn here more about eloquent relationships

Also please take a look at my answer here

Solution 3 - Laravel

By using push on the User model, Laravel is basically recursively calling save on all the related models (which, in this case, is none, since you haven't associated any other models to it yet).

Therefore, in order to accomplish what you're trying to do, you can do first create the user then associate the dealership with it by doing the following:

$user = new User();
$user->email = Input::get('email');
$user->password = Input::get('password');
$user->save();

$dealership = new Dealership();
$dealership->name = Input::get('dealership_name');

$user->dealerships()->save($dealership);
return "User Saved";

However, prior to doing this, you must ensure your User and Dealership models have their relationships set up correctly:

User Model:

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

Dealership Model:

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

Solution 4 - Laravel

This is how I manage to do it.

In your controller: (Laravel 5)

use Auth;

$dealership->user = Auth::user()->ref_user->staff_id;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBeardedInBindaryView Question on Stackoverflow
Solution 1 - LaravelQuasdunkView Answer on Stackoverflow
Solution 2 - LaravelPaul BeleView Answer on Stackoverflow
Solution 3 - LaravelseeARMSView Answer on Stackoverflow
Solution 4 - LaravelThayanandan Samiappan KandiarView Answer on Stackoverflow