<?php
/**
* AppRquest Class
* File: App/Http/Requests/AppRequest.php
*/
namespace App\Http\Requests;
use Illuminate\Http\Request;
class AppRequest
{
protected $req;
public function __construct(Request $req)
{
$this->req = $req;
}
/**
* Proxy the rest of the methods calls to the Request Class
*/
public function __call($method, $args)
{
return call_user_func_array( [ $this->req, $method ], $args );
}
/**
* Proxy writing data to inaccessible properties to the Request Class
*/
public function __set($name, $value)
{
$this->req[$name] = $value;
}
/**
* Proxy reading data from inaccessible properties to the Request Class
*/
public function __get($name)
{
return $this->req[$name];
}
/**
* Decorate the query method
*/
public function query($key, $default = null, $cb = null)
{
$value = $this->req->query($key, $default);
if( null === $cb && is_numeric($value) && is_numeric($default) )
{
$cb = function($value, $default) {
if( $value > $default )
return false;
return true;
};
}
if( is_callable($cb) && !$cb($value, $default) )
{
return $default;
}
return $value;
}
}
/**
* Register AppRquest Class
* File: App\Providers\AppServiceProvider
*/
use App\Http\Requests\AppRequest;
public function register()
{
$this->app->bind(AppRequest::class, function(){
return new AppRequest( request() );
});
}
- By default the Default Validation Closure will be used if the Query String Patameter & the Default Value are both numerical.
- The Query String Patameter value will be returned if there are no validation roles passed.
- The Default Validation Closure will return the default value if the Query String Patameter greater than the Default Value
Example:
http://localhost:8000/users?limit=1 - $limit = 1
http://localhost:8000/users?limit=2 - $limit = 2
http://localhost:8000/users?limit=3 - $limit = 2
http://localhost:8000/users?limit=9 - $limit = 2
use App\Http\Requests\AppRequest;
use App\User;
Route::get('/users', function(AppRequest $req){
$limit = $req->query('limit', 2);
return User::paginate($limit);
});
You can pass a closure as a third parameter to perform a custom validation
http://localhost:8000/users?limit=1 - $limit = 1
http://localhost:8000/users?limit=10 - $limit = 10
http://localhost:8000/users?limit=99 - $limit = 99
http://localhost:8000/users?limit=100 - $limit = 100
http://localhost:8000/users?limit=101 - $limit = 100
Example:
Route::get('/users', function(\SharedKernel\Http\AppRequest $req){
// This will guard the Query String Parameter by returning the default value if
// the limit Query String Parameter is greater than 100
$limit = $req->query('limit', 100, function($value, $default){
if( $value > 100 )
return false;
return true;
});
return App\User::paginate($limit);
});