I would like to have in my applications many models/modules but some of them would be removed for some clients.
Now I have such relation:
public function people()
{
return $this->hasMany('People', 'model_id');
}
and when I run $model = Model::with('people')->get();
it is working fine
But what if the People
model doesn't exist?
At the moment I'm getting:
1/1 ErrorException in ClassLoader.php line 386: include(...): failed to open stream: No such file or directory
I tried with
public function people()
{
try {
return $this->hasMany('People', 'model_id');
}
catch (FatalErrorException $e) {
return null;
}
}
or with:
public function people()
{
return null; // here I could add checking if there is a Model class and if not return null
}
but when using such method $model = Model::with('people')->get();
doesn't work.
I will have a dozens of relations and I cannot have list of them to use in with
. The best method for that would be using some empty relation
(returning null) just to make Eloquent not to do anything but in this case Eloquent still tries to make it work and I will get:
Whoops, looks like something went wrong. 1/1 FatalErrorException in Builder.php line 430: Call to a member function addEagerConstraints() on null
Is there any simple solution for that?
The only solution I could come up with is creating your own
Eloquent\Builder
class.I've called it
MyBuilder
. Let's first make sure it gets actually used. In your model (preferably a Base Model) add thisnewEloquentBuilder
method:In the custom
Builder
class we will override theloadRelation
method and add anif null
check right beforeaddEagerConstraints
is called on the relation (or in your case onnull
)The rest of the function is basically the identical code from the original builder (
Illuminate\Database\Eloquent\Builder
)Now simply add something like this in your relation function and it should all work:
Update: Use it like a relationship
If you want to use it like you can with a relationship it gets a bit more tricky.
You have to override the
getRelationshipFromMethod
function inEloquent\Model
. So let's create a Base Model (Your model obviously needs to extend it then...)Now we need to modify the relation to return an empty collection
And change the
loadRelation
function inMyBuilder
to check for the type collection instead ofnull