-
-
Save egesu/1ba1bab3d748f436f7f1d2708c4c7518 to your computer and use it in GitHub Desktop.
Laravel 5.8+ boolean string to boolean middleware
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Middleware; | |
use Closure; | |
use Illuminate\Http\Request; | |
class BooleanMiddleware | |
{ | |
/** | |
* Handle an incoming request. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @param \Closure $next | |
* @param string|null $guard | |
* @return mixed | |
*/ | |
public function handle(Request $request, Closure $next) | |
{ | |
if ($request->method() === 'GET') { | |
$request->replace($this->transform($request->all())); | |
} | |
return $next($request); | |
} | |
/** | |
* Transform boolean strings to boolean | |
* @param array $parameters | |
* @return array | |
*/ | |
private function transform(array $parameters): array | |
{ | |
return collect($parameters)->map(function ($param) { | |
if ($param == 'true' || $param == 'false') { | |
return filter_var($param, FILTER_VALIDATE_BOOLEAN); | |
} | |
return $param; | |
})->all(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment