Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$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());
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading