I know, that I can fetch Model data based on their relationship existence using with()
or doesntHave()
in Laravel (9), but I never ever want to fetch Model data without a relationship, thus it is annoying to always write the with()
function in all CRUD functions.
Is there a way to pre-filter models without a relationship directly in the Model class?
Adding protected $with = ['foo'];
adds the relationships to every record, but is still including the ones without a relationship.
As an optional bonus to that: Maybe a bypass is nice to have, so that in general all results will have relationship but maybe for one specific path GET /all_data
the pre-selection would be bypassed.
CodePudding user response:
You can enable eager loading by default
if you add the relationship to the $with
property of the model as described here: https://laravel.com/docs/9.x/eloquent-relationships#eager-loading-by-default
The documentation reads:
Sometimes you might want to always load some relationships when retrieving a model. To accomplish this, you may define a $with property on the model:
=====Edit1
Another option is using Global Scopes
https://laravel.com/docs/9.x/eloquent#global-scopes.
You can go from here, you can add some more logic to exclude models without the relationship.
=====Edit2
The extra logic will be adding this from the documentation:
https://laravel.com/docs/9.x/eloquent-relationships#querying-relationship-existence
protected static function boot(){
parent::boot();
static::addGlobalScope('relation', function($builder){
$builder->has('relation')->with('relation');
});
}