Skip to content

Instantly share code, notes, and snippets.

@bonniss
Created October 28, 2019 11:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bonniss/6b0f1269a4035a73a4cd5034b265ff89 to your computer and use it in GitHub Desktop.
Save bonniss/6b0f1269a4035a73a4cd5034b265ff89 to your computer and use it in GitHub Desktop.
A quick guide on Laravel routing

Laravel Routing

Ref: https://laravel.com/docs/5.8/routing

Overview

All Laravel routes are defined in route files, which are located in the routes directory. These files are automatically loaded by the framework.

  • The route/web.php file defines routes that are for your web interface. These routes are assigned the web middleware group, which provides features like session state and CSRF protection.

  • The routes in routes/api.php are stateless and are assigned the api middleware group.

Routes defined in routes/web.php may be accessed by entering the defined route's URL in your browser.

Routes defined in the routes/api.php file are nested within a route group by the RouteServiceProvider. Within this group, the /api URI prefix is automatically applied so you do not need to manually apply it to every route in the file. You may modify the prefix and other route group options by modifying you RouteServiceProvider class.

Available Router Methods

// any HTTP verb
Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);

// Sometimes you may need to register a route that responses to multiple HTTP verbs
Route::match(['get', 'post'], function() {
    //
});

// or responds to all HTTP verbs!
Route::any('/', function() {
    //
});

CSRF Protection

Any HTML forms pointing to POST, PUT or DELETE routes that are defined in the web routes file should include a CSRF token field. Otherwise, the request will be rejected.

<form method="POST" action="/profile">
    @csrf
    ...
</form>

Basic Routing

Simplest

Route::get('foo', function () {
    return 'Hello World';
});

Redirect

// Return a 302 status code
Route::redirect('/here', '/there');

// customize the returned code to 301
Route::redirect('/here', '/there', 301);

// or use specific method to obtain the same goal
Route::permanentRedirect('here', 'there');

View Routes

// first is route, second is view name
Route::view('/welcome', 'welcome');

// Pass data to view as third argument
Route::view('/welcome', 'welcome', ['name' => 'Taylor']);

Accessing the Current Route

$route = Route::current();

$name = Route::currentRouteName();

$action = Route::currentRouteAction();

Route Parameters

Route::get('user/{id}', function($id) {
    return 'User '.$id;
});

// order of input params matter!
Route::get('posts/{post}/comments/{comment}', function ($postId, $commentId) {
    //
});

// Optional params
// make sure to give the route's corresponding variable a default value
Route::get('user/{name?}', function ($name = null) {
    return $name;
});

Route::get('user/{name?}', function ($name = 'John') {
    return $name;
});

Regular Expression Constraints

// Route parameters can be constrained using the where method on the route instance
Route::get('user/{name}', function ($name) {
    //
})->where('name', '[A-Za-z]+');

Route::get('user/{id}', function ($id) {
    //
})->where('id', '[0-9]+');

Route::get('user/{id}/{name}', function ($id, $name) {
    //
})->where(['id' => '[0-9]+', 'name' => '[a-z]+']);

Global Constraints

// `boot` method in `RouteServiceProvider`
/**
 * Define your route model bindings, pattern filters, etc.
 *
 * @return void
 */
public function boot()
{
    Route::pattern('id', '[0-9]+');

    parent::boot();
}

// Apply to all routes using that parameter name
Route::get('user/{id}', function ($id) {
    // Only executed if {id} is numeric...
});

Form Method Spoofing

HTML form do not support PUT, PATCH or DELETE actions. You will need to add a hidden _method field to the form.

<form action="/foo/bar" method="POST">
    <input type="hidden" name="_method" value="PUT">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>

<!-- User @method in Blade -->
<form action="/foo/bar" method="POST">
    @method('PUT')
    @csrf
</form>

Fallback Routes

Using the Route::fallback method, you may define a route that will be executed when no other route matches the incoming request. Typically, unhandled requests will automatically render a "404" page via your application's exception handler.

Route::fallback(function () {
    // all middleware in the web middleware group will apply to the route
    // You are free to add additional middleware to this route as needed
});

Named Routes

Basic

// Named routes allow the convenient generation of URLs or redirects for specific routes.
Route::get('user/profile', function () {
    //
})->name('profile');

Route::get('user/profile', 'UserProfileController@show')->name('profile');

// Once you have assigned a name to a given route, you may use the route's name when generating URLs or redirects via the global `route` function
// Generating URLs...
$url = route('profile');

// generating redirects...
return redirect()->route('profile');
// with parameters
return redirect()->route('profile',['id'=>1]);

Inspecting the current route

// If you would like to determine if the current request was routed to a given named route, you may use the `named` method on a Route instance.

/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
public function handle($request, Closure $next)
{
    if ($request->route()->named('profile')) {
        //
    }

    return $next($request);
}

Route Groups

  • Route groups allow you to share route attributes, such as middleware or namespaces, across a large number of routes without needing to define those attributes on each individual route.

  • Shared attributes are specified in an array format as the first parameter to the Route::group method.

  • Nested groups attempt to intelligently "merge" attributes with their parent group.

Middleware

To assign middleware to all routes within a group, you may use the middleware method before defining the group.

Route::middleware(['first', 'second'])->group(function () {
    Route::get('/', function () {
        // Uses first & second Middleware
    });

    Route::get('user/profile', function () {
        // Uses first & second Middleware
    });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment