Lumen middleware to use Route parameters as objects (like Laravel does)
This is a route middleware.
composer require spinyman/lumen-route-param-to-object-middleware
- Register middleware in
./bootstrap/app.php
:$app->routeMiddleware( [ 'param2object' => \SpinyMan\LumenRouteParamToObject\Middleware\RouteParamToObject::class, ] );
- Add it to any group route (ex.: RouteServiceProvider):
$this->router->group( [ 'middleware' => 'param2object', ], static function (\Laravel\Lumen\Routing\Router $router) { // your code goes here } );
//router
$this->router->group(
[
'middleware' => 'param2object',
],
static function (\Laravel\Lumen\Routing\Router $router) {
$this->router->get(
'/books/{book}',
'BookController@show'
);
}
)
class Book extends \Illuminate\Database\Eloquent\Model
{
protected $table = 'books';
}
class BookController extends \Laravel\Lumen\Routing\Controller {
public function show(\Laravel\Lumen\Http\Request $request, Book $book)
{
$bookId = $book->getKey();
// your code goes here
}
}
//router
$this->router->group(
[
'middleware' => 'param2object',
],
static function (\Laravel\Lumen\Routing\Router $router) {
$this->router->get(
'/namer/{namer}',
'NamerController@run'
);
}
)
// Namer class
class Namer
{
private $name;
public function __construct(string $name)
{
$this->name = $name;
}
public function getName(): string
{
return ucfirst(
strtolower($this->name)
);
}
}
class NamerController extends \Laravel\Lumen\Routing\Controller
{
public function run(\Laravel\Lumen\Http\Request $request, Namer $namer)
{
return $namer->getName();
}
}