PHPackages                             petrelli/scoped-controller - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Framework](/categories/framework)
4. /
5. petrelli/scoped-controller

ActiveLibrary[Framework](/categories/framework)

petrelli/scoped-controller
==========================

Very simple controller that automatically call scopes based on URL parameters

v0.9.4(6y ago)12.7k1MITPHPPHP ^7.0CI failing

Since Sep 7Pushed 5y ago1 watchersCompare

[ Source](https://github.com/ferpetrelli/scoped-controller)[ Packagist](https://packagist.org/packages/petrelli/scoped-controller)[ RSS](/packages/petrelli-scoped-controller/feed)WikiDiscussions master Synced 6d ago

READMEChangelog (5)Dependencies (1)Versions (6)Used By (0)

Scoped Controller
=================

[](#scoped-controller)

Scoped Controller is a very simple Laravel package (&lt;80 LOC) that will allow you to build queries and cleanup your controllers by executing scopes based on request parameters.

Inspired on the Ruby on Rails gem [Has Scope](https://github.com/plataformatec/has_scope).

Install
=======

[](#install)

Just include it in your composer.json file

```
composer require petrelli/scoped-controller

```

Or add:

```
"petrelli/scoped-controller": "0.9.*"

```

And run `composer update`.

Basic Usage
===========

[](#basic-usage)

Imagine we have a `Book` model with two filters, by year and by author.

URL parameters might look like the following:

```
# Get books filtered by year == 2020
/books?byYear=2020

# Get books filtered by author == cortazar
/books?byAuthor=cortazar

# Get books filtered by year and author
/books?byYear=1961&byAuthor=borges

```

Steps
-----

[](#steps)

1. Create your controller and be sure to inherit from `Petrelli\ScopedController\BaseController`.
2. Define which class will hold your collection with the `$entity` variable. Usually an Eloquent Model, but could be any class that respond to scopes.

```
protected $entity = Book::class;
```

3. Now define the `$scopes` variable as an Array following the pattern `[ URLparameter => scopeName, .... ]`

```
use Petrelli\ScopedController\BaseController;

class EventsController extends BaseController {

// Here as an example we have two scopes: year and author.
// They will be called if we receive the parameters
// byYear and byAuthor respectively.
protected $scopes = [
    'byYear'   => 'year',
    'byAuthor' => 'author',
];

}
```

4. Now to get a filtered collection simply call `$this->collection()`. You can use any available function. If using Eloquent, you could use `get()`, `paginate(...)`, or anything you need to chain.

```
$items = $this->collection()->get();
$items = $this->collection()->paginate(static::PER_PAGE);
```

Customizing the scopes chain
============================

[](#customizing-the-scopes-chain)

We provide a controller function named `beginOfAssociationChain()` that you could overload. In there we build the base query over which we will apply all of our scopes.

For example:

```
protected function beginOfAssociationChain()
{
    return Book::published()->where('library', 'NYC');
}
```

Here every time we call `$this->collection()` as previously described we will be executing the `published()` scope, and also filtering books where 'library' is 'NYC'.

```
$items = $this->collection()->get();
$items = $this->collection()->paginate(static::PER_PAGE);
```

Applying scopes manually
========================

[](#applying-scopes-manually)

We provide the function `applyScopes($query)` in case you want to manually apply your scopes to a query. As always, which scope will be triggered is a function of the request parameters.

```
// Controller function
public function index()
{
    $items = $this->applyScopes(Book::query())->get();
}
```

Extra functionality
===================

[](#extra-functionality)

Scopes with multi-value parameters
----------------------------------

[](#scopes-with-multi-value-parameters)

If you need to define a multi-value parameter just pass it as an array and define the scopes as the following:

```
// Here as an example we have two scopes: year and author.
// They will be called if we receive the parameters
// byYear and byAuthor respectively.
protected $scopes = [
    'byYear'   => 'year',
    'byAuthor' => 'author',
    'sortBy'   => ['sort_by' ['field', 'direction']],
];
```

Defining the scope as an array will allow you to pass multiple parameters to it coming from the URL as arrays.

Multi-value scopes in action
----------------------------

[](#multi-value-scopes-in-action)

```
# Get books filtered by year = 2018 and sorted by author in alphabetical order
/books?byYear=2018&sortBy['field']=author&sortBy['direction']=asc

# Get books filtered by author = borges and sorted by date
/books?byAuthor=borges&sortBy['field']=date&sortBy['direction']=desc

```

You get the idea. The scope is nothing but a simple two parameter element.

```
public function scopeSortBy($query, $value, $direction = 'asc')
{
    //...
}

```

Of course you can generalize to use any number of parameters. Simply add it to the $scopes definition.

Check if any filter is present
------------------------------

[](#check-if-any-filter-is-present)

Common use case, if you need to check if any scope is present:

```
// Returns true/false
$this->hasAnyScope()
```

Use specific scopes for different actions
=========================================

[](#use-specific-scopes-for-different-actions)

Because `$this->collection()` is returning a Query Builder (when using Eloquent for example), you could keep chaining methods and scopes as you would normally do:

```
public function index()
{
    // Return Books triggering defined scopes
    $items = $this->collection()->get();
}

public function indexBestSellers()
{
    // Return Books triggering defined scopes + bestSeller scope
    $items = $this->collection()->bestSeller()->get();
}
```

License
=======

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

27

—

LowBetter than 49% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity19

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~140 days

Total

5

Last Release

2250d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/4fc70d39bb6fe2c649062145018204aba8004821722ec6699cb456c18f4db005?d=identicon)[petrelli](/maintainers/petrelli)

---

Top Contributors

[![ferpetrelli](https://avatars.githubusercontent.com/u/421480?v=4)](https://github.com/ferpetrelli "ferpetrelli (9 commits)")

---

Tags

controllerfilterlaravelparametersscopescontrollerfiltersscopesA17scoped

### Embed Badge

![Health badge](/badges/petrelli-scoped-controller/health.svg)

```
[![Health](https://phpackages.com/badges/petrelli-scoped-controller/health.svg)](https://phpackages.com/packages/petrelli-scoped-controller)
```

###  Alternatives

[htmlburger/wpemerge

A micro framework which modernizes WordPress as a CMS development by providing tools to implement MVC and more.

456137.8k8](/packages/htmlburger-wpemerge)[mmoreram/controller-extra-bundle

Some specific controller annotations

151217.3k5](/packages/mmoreram-controller-extra-bundle)[martynbiz/slim3-controller

Provides controller functionality to Slim Framework v3. Also includes PHPUnit TestCase for testing controllers.

2814.4k1](/packages/martynbiz-slim3-controller)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
