Home > database >  Laravel update one field of a model relation
Laravel update one field of a model relation

Time:09-26

I am trying to update only one field on a models relation but it keeps returning it as null and I cant figure out why;

The profile is a belongsTo relationship

$user = User::find(1);

$user->profile->api_key = 'apikeyhere';
$user->save();

After i do this and then run dd($user->profile) .. The api_key field is null instead of the actual value.

CodePudding user response:

Using two query

$user = User::find(1);
$user->profile()->update([ 'api_key' => 'apikeyhere']);

Using One query

Profile::where('user_id', 1)->update([ 'api_key' => 'apikeyhere']);

CodePudding user response:

Update the field using the relation.

$user = User::find(1);
$user->profile()->update(['api_key' => 'api_key value']);
  • Related