Friday, April 13, 2018

Laravel return empty relationship on model when condidtion is true - development

Laravel return empty relationship on model when condidtion is true

I have a model where I want to return a empty value when a condition happens, but when I try to get the model:

Model::with('shop')->find(id);

I get this error:

“Call to a member function addEagerConstraints() on null”

This is the code I’m trying:

public function shop(){
    if(true) {
        return null;
    }
    return $this->belongsTo('AppModelsShop');
}

How is the proper way to return nothing when a condition is true on Laravel relationships?

There’s the full error trace:

FatalThrowableError {#441 ▼
  #message: "Call to a member function addEagerConstraints() on null"
  #code: 0
  #file: "app/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php"
  #line: 451
  #severity: E_ERROR
  -trace: array:42 [▼
    0 => array:3 [▼
      "call" => "IlluminateDatabaseEloquentBuilder->loadRelation()"
      "file" => "app/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:429"
      "args" => array:3 [▶]
    ]
    1 => array:3 [▼
      "call" => "IlluminateDatabaseEloquentBuilder->eagerLoadRelations()"
      "file" => "app/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:174"
      "args" => array:1 [▼
        0 => array:3 [▼
          0 => Product {#444 ▶}
          1 => Product {#445 ▶}
          2 => Product {#446 ▶}
        ]
      ]
    ]
    2 => array:3 [▼
      "call" => "IlluminateDatabaseEloquentBuilder->get()"
      "file" => "app/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:105"
      "args" => array:1 [▼
        0 => array:1 [▼
          0 => "*"
        ]
      ]
    ]



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-return-empty-relationship-on-model-when-condidtion-is-true/
via Lzo Media

No comments:

Post a Comment