Saving one to one relation in Laravel
$user = User::findOrFail(1);
$company = $user->company ?: new Company;
$company->name = 'Test';
$user->company()->save($company);
I'm trying to save (so create or update) a user's company
You can do exactly that with the updateOrCreate method:
User::findOrFail(1)->company()->updateOrCreate([],['name' => 'xyz']);
The first parameter of updateOrCreate
is an empty array, because the companies id
is determined by the hasOne
relationship $user->company()
.
And by the way, I would recommend not using an auto-increment id field in a hasOne
relationship. If you set user_id
as primary in your company table, its technically not possible to create duplicate company rows for one user. Check out my blog post for more.
Creating and updating need to treat differently. So check the existence of company attribute first.
$user = User::with('company')->findOrFail(1);
if ($user->company === null)
{
$company = new Company(['name' => 'Test']);
$user->company()->save($company);
}
else
{
$user->company->update(['name' => 'Test']);
}
Note that hasOne()
does not guarantee that you will have one-to-one relationship, it just telling Eloquent how to create query. It works even you have multiple Company
refer to same User
, in such case when you call $user->company
you will get first Company
in the result data set from database.