Download the PHP package petrelli/scoped-controller without Composer
On this page you can find all versions of the php package petrelli/scoped-controller. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package scoped-controller
Scoped Controller
Scoped Controller is a very simple Laravel package (<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.
Install
Just include it in your composer.json file
Or add:
And run composer update
.
Basic Usage
Imagine we have a Book
model with two filters, by year and by author.
URL parameters might look like the following:
Steps
-
Create your controller and be sure to inherit from
Petrelli\ScopedController\BaseController
. -
Define which class will hold your collection with the
$entity
variable. Usually an Eloquent Model, but could be any class that respond to scopes. -
Now define the
$scopes
variable as an Array following the pattern[ URLparameter => scopeName, .... ]
- Now to get a filtered collection simply call
$this->collection()
. You can use any available function. If using Eloquent, you could useget()
,paginate(...)
, or anything you need to 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:
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'.
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.
Extra functionality
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:
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
You get the idea. The scope is nothing but a simple two parameter element.
Of course you can generalize to use any number of parameters. Simply add it to the $scopes definition.
Check if any filter is present
Common use case, if you need to check if any scope is present:
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:
License
The MIT License (MIT). Please see License File for more information.