Reputation: 1748
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?
Upvotes: 2
Views: 4361
Reputation: 24671
$profile = new UserProfile( array(
'name' => $i['name'],
'surname' => $i['surname'],
// ...
) );
$user = new User( array(
'username' => $i['username'],
// ...
) );
$profile = $user->profile()->save($profile);
See the related documentation entry for more information.
Upvotes: 1
Reputation: 11374
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);
Upvotes: 6