TheBreaker
TheBreaker

Reputation: 41

Create multiple objects from api post in laravel

Im at a bit of a loss. I have an api that will create a user upon a request. This is done no problem.

I also want to create another controller action or add to my current action the ability to create an address for the same user.

Is there an easy way to do this? Or should I stick to the

$user = new User(Input::all());
$user->save();

$address = new Address(Input::all());
$address->save();

Upvotes: 0

Views: 795

Answers (3)

TheBreaker
TheBreaker

Reputation: 41

I was able to figure it out!

I wound up utilizing the Ardent package to help me validate my models before they hit the save method.

if my models didnt validate i will return all the errors to the user. If they did validate my models would be created.

As for the association I am using the has many relation ship on the User and belongs to on the Address. I used the following to save the address to the user

$address = $user->address()->save($address);

however I could only preform this after the initial user object was saved.

Thanks for all the responses guys they lead me in the right direction!

Upvotes: 0

Kousha
Kousha

Reputation: 36219

This is a relationship problem. An address to a user will most likely be One-to-One (i.e., each Userhas a unique Address). A User might have an Address, but an Address must have a User. So in essence, the Address belongs to User.

Create two tables users and addresss, and add user_id to the address table as a column.

Then you define your relationships:

// In your User.php model
public function address()
{
    return $this->hasOne('Address');
}

// In your Address.php model
public function user()
{
    return $this->belongsTo('User');
}

Note when you use the correct notation, you can just define the model name, and not specify the pivot column. That is why I have defined the class addresss with an extra 's' to make it plural. I personally don't care about the spelling and rather Laravel take care of everything. Otherwise read the documentation on how to define the pivot column

Then you can use associate easily:

$user = new User();
// Fill $user however you want

$address = new Address();
// Fill $address however you want

$user->associate($address);
$user->save();

Upvotes: 0

Chris Magnussen
Chris Magnussen

Reputation: 1527

You should set up relationships between your User and Address model - http://laravel.com/docs/eloquent#relationships and use associate/sync() to connect the dots.

Upvotes: 1

Related Questions