mardi 1 mars 2016

Laravel 5: no foreign key when saving related models

I have a simple one-to-one relationship between a User and a Profile, I'm trying to create a user and save their profile with the foreign key in one go and avoid having to pass the primary key and do two save() calls.

Laravel will try to insert the corresponding Profile values without the id pointing back to the user. What am I doing wrong ?

class User extends Model
{
    public function profile()
    {
        return $this->hasOne('App\Profile');
    }
}


class Profile extends Model
{
    protected $table = 'user_profile';

    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

class UserController extends Controller
{

  public function create(Request $request)
  {

    $this->validate($request, [
    ...
    ]) ;

    $user = new User() ;
    $profile = new Profile() ;

    $user->name = $request->input('name') ; 
    ...

    $profile->first_name = $request->input('first_name') ;
    $profile->last_name = $request->input('last_name') ;
    ...

    $user->profile()->save($profile) ;
    // $profile->user()->save($user) ; // doesn't work

    // $profile->user()->associate($user) ; // doesn't work
    // $profile->save() ;    
  }
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire