Created
August 12, 2019 16:59
-
-
Save yedincisenol/4951db2b01ac5d2bfebf969b1e1f6866 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) | |
{ | |
$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
@egesu Your welcome :)