Exclude Model Entities From Eloquent With the Laravel Exclusions Package

Packages

June 11th, 2021

laravel-exclusions-featured.png

Laravel Excludable is a package to exclude models from Eloquent queries. You can define a subset of models that should be excluded when you query an individual model or a collection:

1use App\Models\Article;
2
3$article = Article::query()->findOrFail(1)
4
5$article->addToExclusion();
6
7$article->excluded(); // returns true
8
9// Throws NotFoundHttpException after exclusion
10Article::findOrFail(1);

Similar to the soft deletes functionality, you can include “excluded” models with the following scope:

1Article::withExcluded()->get();
2
3// Or only return excluded models
4Article::onlyExcluded()->get();

Finally, here’s an example of how to configure Eloquent models to support exclusions:

1<?php
2
3namespace App\Models;
4
5use HFarm\Excludable\Excludable;
6
7class Article extends Model
8{
9 use Excludable;
10
11 protected $fillable = [
12 'title',
13 'body',
14 ];
15}

You can learn more about this package, get full installation instructions, and view the source code on GitHub.


This package was submitted to our Laravel News Links section. Links is a place the community can post packages and tutorials around the Laravel ecosystem. Follow along on Twitter @LaravelLinks

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.