0

Phone BelongsTo User. Now how i insert phone & user data both through belongsTo Relationship & auto get user_id foreign key in phone table. Here I try this code but not work.

$phoneData = $request->get('phone');
$userData = $request->get('name');
$phone->user()->create($userData);
$phone->create($phoneData);

Here is in form input field

2 Answers2

0

Something like this:

$userData  = $request->get('name');
$phoneData = $request->get('phone');

$user = User::create($userData);
$user->phones()->save(new Phone($phoneData));

Of course you'll need to define the relationship on the User model as well:

// \App\User.php
public function phones()
{
    return $this->hasMany(\App\Phone::class);
}
anakadote
  • 322
  • 2
  • 11
0

You can't create a phone without an user, it's not recommended because the foreign key constraint, that you must have in your database, won't let you..

$userData  = $request->get('name');
$phoneData = $request->get('phone');

$phone = new Phone();
$phone->user()->associate(User::create($userData));
$phone->save();

Maybe you are looking for something like this...

for updating..

$phone = isset($phoneData['id']) 
   ? Phone::where('id', $phoneData['id'])->first() : new Phone(); 
$phone->user()->associate(User::firstOrCreate(
  ['email' =>$userData['email']], .... extra data from user));
$phone->save();
Walter Cejas
  • 1,924
  • 1
  • 12
  • 22