Laravel Routing Tricks

Laravel Routing 

Some Laravel Routing Tricks  are below;

  • Nested Route groups
  • Catch-all view route
  •  Internal dispatch


Nested Route Groups

Route groups are a great way to use the same prefixes, filters to a group of routes.

Route::group(['prefix'=> => 'account', 'as' => 'account.'], function()
{
    Route::get('login', ['as' => 'login', 'uses' => AccountController::Class.'@getLogin']);
});
<a href="{{ route('account.login') }}">Login</a>

 Catch-all View Route

Laravel’s view() helper to return views to the user with a dot syntax.


// app/Http/routes.php
Route::group(['middleware' => 'auth'], function()
{
    Route::get('{view}', function($view)
    {
        try {
            return view($view);
        } catch (\Exception $e) {
            abort(404);
        }
    })->where('view', '.*');
});

 Internal Dispatch

// api controller
public funciton show(Car $car)
{
    if (Input::has('fields')) {
        // do something
    }
}
// internal request to api - fields are lost
$request = Request::create('/api/cars/' . $id . '?fields=id,color', 'GET');
$response = json_decode(Route::dispatch($request)->getContent());
// internal request to api - with fields
$originalInput = Request::input();
$request = Request::create('/api/cars' . $id . '?fields=id,color', 'GET');
Request::replace($request->input());
$response = json_decode(Route::dispatch($request)->getContent());
Request::replace($originalInput);