Last active
February 21, 2022 12:44
-
-
Save westphalen/c3cd187007e0448bcb7fca1de091e4df to your computer and use it in GitHub Desktop.
Get, set and forget route parameters on Lumen's array-based Request Router, avoiding `$request->route($key)` problem.
This file contains 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 | |
/** | |
* Created by PhpStorm. | |
* User: sune | |
* Date: 09/03/2017 | |
* Time: 17.30 | |
*/ | |
namespace App\Support; | |
use Illuminate\Http\Request; | |
/** | |
* This helper makes it easier to work with parameters on the Lumen array-based router. | |
* | |
* Class Route | |
* | |
* @package App\Support | |
*/ | |
class RouteParam | |
{ | |
/** | |
* Get a route parameter from the request. | |
* | |
* @param Request $request | |
* @param string $param | |
* @return boolean | |
*/ | |
static public function exists(Request $request, $param) | |
{ | |
return Arr::exists($request->route()[2], $param); | |
} | |
/** | |
* Get a route parameter from the request. | |
* | |
* @param Request $request | |
* @param string $param | |
* @param mixed|null $default | |
* @return mixed | |
*/ | |
static public function get(Request $request, $param, $default = null) | |
{ | |
return Arr::get($request->route()[2], $param, $default); | |
} | |
/** | |
* Set a route parameter on the request. | |
* | |
* @param Request $request | |
* @param string $param | |
* @param mixed $value | |
*/ | |
static public function set(Request &$request, $param, $value) | |
{ | |
$route = $request->route(); | |
$route[2][$param] = $value; | |
$request->setRouteResolver(function () use ($route) { | |
return $route; | |
}); | |
} | |
/** | |
* Forget a route parameter on the Request. | |
* | |
* @param Request $request | |
* @param string $param | |
*/ | |
static public function forget(Request &$request, $param) | |
{ | |
$route = $request->route(); | |
Arr::forget($route[2], $param); | |
$request->setRouteResolver(function () use ($route) { | |
return $route; | |
}); | |
} | |
} |
Thanks!!!!! It was help me very much
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this! Helped clean up my code.
Although I think you are missing the 'use Illuminate\Support\Arr;' at the top which allows you to use Arr object?