I'm trying to extend the Laravel 5.6 router class to add some handy methods to register routes.
I have created a class that extends the Illuminate\Routing\Router
class like this:
Namespace App\Overrides;
use Illuminate\Routing\Router as LaravelRouter;
class Router extends LaravelRouter
{
public function apiReadResource($name, $controller, array $options = [])
{
$this->resource($name, $controller, array_merge([
'only' => ['index', 'show'],
], $options));
}
public function apiWriteResource($name, $controller, array $options = [])
{
$this->resource($name, $controller, array_merge([
'except' => ['index', 'show', 'edit', 'create', 'destroy'],
], $options));
}
public function apiRelationshipResources($name, $controller, array $relationships, array $options = [])
{
foreach($relationships as $relationship)
{
$this->get(
$name.'/{id}/'.$relationship,
[
'uses' => $controller . '@' . $relationship,
'as' => $name . '.' . $relationship,
]
);
}
}
}
I have registered my extended class like this in the default App\Providers\RouteServiceProvider
:
namespace App\Providers;
use Illuminate\Routing\Router;
use App\Overrides\Router as APIRouter;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
/**
* This namespace is applied to your controller routes.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'App\Http\Controllers';
public function register()
{
$this->app->singleton('router', function ($app) {
return new APIRouter($app['events'], $app);
});
}
/**
* Define your route model bindings, pattern filters, etc.
*
* @return void
*/
public function boot()
[more code...]
}
In the routes file I call my own custom methods like this: Route::apiWriteResource('users', 'UserController');
or like this Route::apiRelationshipResources('users', 'UserController', ['reviews']);
All routes are registered and show up correctly in php artisan route:list
, but none of the routes actually work. They all gives the standard 404 page.
What am I doing wrong? What have I missed?