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.
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.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With