Laravel 8 override relationship value after get the result

My controller looks like this:

  public function show($id)
    { 
        $model = MyModel::with([
            'model2.model3.model4:id,value',
            ...
        ]);

        if (myCondition) {
            unset($model->model2->model3->model4);
            $model->model2->model3->model4 = Model4::where('value', 'Some Value')->first();
        }

        return $audit;
    }

In certain condition I’d like to override the result from the query with another value from the Model4 to return the good data to the client.

But I want to know if there is another way with laravel to do that. Actually I have to use unset and then push the new content if I want to change the value of the model4 property. If I don’t use unset the object isn’t changed, the value new value assigned to model4 is ignored I don’t know why I can’t just write this line

$model->model2->model3->model4 = Model4::where('value', 'Some Value')->first();

So I want to know why I can’t see changes in my json object when I don’t use unset and I want to know if there is anotehr way to deal with laravel for my situation ?

>Solution :

You can simply use setRelation method.

if ($myCondition) {
    $model->model2->model3->setRelation('model4', Model4::where(...)->first());
}

Leave a Reply