Reputation: 341
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
Upvotes: 0
Views: 1291
Reputation: 887
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
.
Upvotes: 1
Reputation: 13
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. :-)
Upvotes: 0