Skip to content

Instantly share code, notes, and snippets.

@westphalen
Last active February 21, 2022 12:44
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save westphalen/c3cd187007e0448bcb7fca1de091e4df to your computer and use it in GitHub Desktop.
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.
<?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;
});
}
}
@christhomas
Copy link

christhomas commented May 17, 2019

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?

@LucasSantosDev
Copy link

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