I have a situation where I fetch a model in Laravel. Something like this:
$user = User::with('subscription')->where('id', '=', 123)->first();
If I then later try and do something like this:
$user->firstname = 'John';
$user->save();
I get an SQL error because it says that there is no DB field called "subscription" It seems like the relationship is being treated as a DB field when saving. Is that right? Am I mean to
unset($user->subscription)
before saving?
Is it not possible to update a model if there is a relationship attached? Does it have to be removed before saving?
I found what was causing this. In a previous place in my code I was trying to update the relationship. Accidentally I was assigning the subscription as an attribute to my user object. This was not a Laravel issue.
try this
create new user object
$user = new User;
$user->firstname = 'John';
$user->save();
Same code is working for me. What laravel version are you using?
$psc = Subject::with('group')->where('group_id', 1)->first();
$psc->group->name = 'PSC';
$psc->group->save();
dd($psc->group);
$psc->name = 'Science';
$psc->save();
dd($psc->name);