When I use ModelName::with('somerelation')->get()
with Laravel Eloquent, if the model doesn’t have this relationship I get Call to undefined relationship [somerelation] on model [AppSomeModel]
error.
But for polymorphic relations, I get collection of all related models and I would like to use with('somerelation')
and get null
if relationship is not defined. Is there any way to avoid error and return null from with() or any way to use with conditionally?
Advertisement
Answer
What I do on all my Laravel projects is creating a Model class that extends Eloquent Model and all my models will extend my Model class, so I can override some methods from Eloquent Model using my rules.
So you can create a new class (I call it Model) and override the method with with a try/catch block retuning null in the case this exception is thrown by eloquent model.
Example:
namespace App; use IlluminateDatabaseEloquentModel as EloquentModel; use IlluminateDatabaseEloquentRelationNotFoundException; abstract class Model extends EloquentModel { public static function with($relations) { try { return parent::with($relations); } catch (RelationNotFoundException $e) { return null; } } }