Saving related records in laravel

laravel relationships
laravel hasonethrough save
laravel save hasmany relationship
laravel sync with pivot
laravel relationship with condition
laravel without relationship
polymorphism in laravel
laravel many to many sync

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.

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

How to save Eloquent Model with relations in one go?, Now the problem is when something goes wrong in the related model This is to ensure that when you save the captain, the records of the ship found are also  Laravel logs don't write when queued by beanstalkd daemon. laravel-4,beanstalkd. This was caused by the fact that when run as a daemon the app instance stays in memory perpetually, so any code changes (such as introducing log lines) won't be reflected.

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

Eloquent: Relationships - Laravel, I am trying to save data with eloquent relationship. I have following three be of use to you. ( the link to it is : https://laravel.com/docs/5.3/eloquent-relationships ). Eloquent has one less-known function called withCount(): it helps to get the amount of related records inside of the main object. It also works with two layers deep, inside of hasManyThrough relations. Let's take a look.

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');
}

Save data with eloquent relations, Cause you can not call the save method on related model/object. You need to call attach as @Goldenstat mentioned. Posted 4 years ago by  Saving related records in laravel. 3. how to use Laravel Eloquent push() function? 5. Saving a model with multiple foreign keys in Laravel 4. 0. PHP / Laravel

This is how I manage to do it.

In your controller: (Laravel 5)

use Auth;

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

Saving with relations (hasOne, hasMany), Now I am trying to figure out how I save an Album with multiple you use ->​saveMany() Laravel does pretty much the same thing, loops them and AlbumFile saving, so there would be a Album record with no children which I  Defining Inverse One To Many Relationship in Laravel. As we have defined the hasMany relationship on Brand model which return the related records of Product model, we can define the inverse relationship on the Product model. Open your app/Product.php model file and add a new method called brand() in it which will return the related brand of a

Save related model, 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. How do I save multiple rows of data on laravel 5? The structure of the table that I use: Table events: id,subject,description,start time,end time. Table event_addresss: id,event_id,address. Table event_prices: id,event_id,class_room,price. Information: Class room contains VIP class, grade 1, grade 3, grade 3, economy class.

Saving related records in laravel, In an application there is often a relationship between the database tables. The Eloquent determines the foreign key of the relationship based on the model name. In cases as Recursively Saving Models & Relationships. By default, Laravel will use the fully qualified class name to store the type of the related model. For instance, given the one-to-many example above where a Comment may belong to a Post or a Video , the default commentable_type would be either App\Post or App\Video , respectively.

Laravel (5.7) Eloquent Relationships, The save Method; The create Method; Belongs To Relationships; Many To Eloquent determines the foreign key of the relationship based on the model name. To create a new record in the database, create a new model instance, set attributes on the model, then call the save method: <?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Flight; use Illuminate\Http\Request; class FlightController extends Controller { /** * Create a new flight instance.

Comments
  • Which part of the code get's the dealership ID?
  • Sorry, it would be helpful if I included code from my models too I suppose, haha. laravel.io/bin/N7Pm
  • Thanks! I feel like this got me closer...I've tried using the example to associate a dealership with a user and get this error "Illuminate \ Database \ QueryException SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'dealership_id' cannot be null (SQL: insert into users (email, password, dealership_id, updated_at, created_at) values (testemail@email.com, y$mItUgj2h4JiMi666a3DHROHahjZuRDcgqCaMVDaO..TpurSMVJnWG, , 2014-04-22 19:59:56, 2014-04-22 19:59:56))"
  • So, I know that means I need to get the dealership_id into the users table, not sure how to do that. I don't have a foreign-key reference set up on my migration for the users table, could adding a foreign-key rule automagically fix this? Thanks again!
  • @SteveBalistreri I guess you'll have to save() the new dealership first before associating it :) new Dealership() creates an object, but does not save it yet, so it has no ID. You have to call the save-method manually. Alternatively you can do it with create(): Dealership::create(array('name' => Input::get('dealership_name'))); this automatically saves the newly created object so it has an ID to associate with.
  • Downvoting silently for no effing reason 6 months after the answer was posted? Yeah, way to go, random stranger!
  • can you please describe me what do you mean by $user->dealership()->associate($dealership); $user->save();
  • Thanks, I think I've got my eloquent relationships set up correctly. I made a paste here link. Users table does have a 'dealership_id' column. Still doesn't seem to be creating the dealership, and associating the dealership id with the user.
  • Updated, please take a look at my answer here : stackoverflow.com/questions/23183394/… . What i think, and from examples, it turns out that first you need to save the base model ( i.e.) the user, and the use push() to update
  • Yes, push() does not work with new records. See this issue: github.com/laravel/framework/issues/4641 And considering that push() is not documented much, it seems safer to use save().
  • what about if saving related data / insert new related record with push() instead of save(), is it possible ?
  • push() does not work with new records. See this issue: github.com/laravel/framework/issues/4641 And considering that push() is not documented much, it seems safer to use save().
  • U have errors in relations in your answer. According to model, U don't have method dealerships, because User belongsTo Dealership