php - setrelation method doesn't work in laravel

My user relationship is :

    public function country()
    {
        return $this->belongsTo(Country::class);
    }

and the query is :

  $user = User::with('country')->first();

I want to check if the country is empty replace that with a default data or anything

so first I tried like this :

if(empty($user->country)){
$user->country = "some default value";
}

and It didn't work after searching I try this :

if(empty($user->country)){
$user->setRelation('country' , 'some default value');
}

and again it doesn't work for me. the "setRelation" remove the country key in the user's object

Answer

Solution:

If empty / null received in eloquent result relation key, then set defaultOject can be set as follows:

For single relation:

$modelInstance = $modelInstance->setRelation('relationName', $relationModelObject)

For multiple relation:

$modelInstance = $modelInstance->setRelation('relationName', collect([$relationModelObject]))

Multiple relation example:

$defaultMedia = new Media;
$defaultMedia->id = 0;
$defaultMedia->file_name = 'defaultImage.jpg';

$result = Post::with('media')->get();

$result->transform(function ($post, $key) use($defaultMedia) {
    if($post->media->count() == 0) {
        $post->setRelation('media', collect([$defaultMedia]));
    }
    return $post;
});

return $result;

Now, in final $result you shall get $defaultMedia when relation returned null.

Answer

Solution:

It does not work that way because country is not a direct attribute/column of the user.

You can change your code like this.

if(empty($user->country)){
   $user->country->update([
     'name' => "some default value"
   ]);
}

Hope it works. :-)

Source