Laravel save with relation

eloquent, laravel, php

Solution

You should create your `Profile` object and then attach it to your user.

$u                      = new User();
$u->username            = $i['username'];
$u->email               = $i['mail'];
$u->password            = Hash::make( $i['password'] );
$u->type                = 0;
$u->save();

$profile = new Profile();
$profile->id         = $u->id;
$profile->name       = $i['name'];
$profile->surname    = $i['surname'];
$profile->address    = $i['address'];
$profile->number     = $i['strnum'];
$profile->city       = $i['city'];
$profile->ptt        = $i['ptt'];
$profile->mobile     = $i['mobile'];
$profile->birthday   = $i['year'].'-'.$i['mob'].'-'.$i['dob'];
$profile->newsletter = $i['news'];

$u->profile()->save($profile);

Problem

How to save new user with relations? User model: ``` public function profile(){ return $this->hasOne('Profile','id'); } ``` Profile model: ``` protected $table = 'users_personal'; public function user(){ return $this->belongsTo('User','id'); } ``` Main function: ``` $u = new User; $u->username = $i['username']; $u->email = $i['mail']; $u->password = Hash::make( $i['password'] ); $u->type = 0; $u->profile->id = $u->id; $u->profile->name = $i['name']; $u->profile->surname = $i['surname']; $u->profile->address = $i['address']; $u->profile->number = $i['strnum']; $u->profile->city = $i['city']; $u->profile->ptt = $i['ptt']; $u->profile->mobile = $i['mobile']; $u->profile->birthday = $i['year'].'-'.$i['mob'].'-'.$i['dob']; $u->profile->newsletter = $i['news']; $u->push(); ``` If I do this I get an error: Indirect modification of overloaded property User::$profile has no effect How can I save user profile when creating a new User?

Original source