Basic to Advance Routing in Laravel

Basic to Advance Routing in Laravel

Basic to basic web project have implement routing concept that why we called it basic routing even we go deep its still be basic because its just go to some URL just it. There we can check some basic to advance routing method used in Laravel project that can make your life easier.

Routing in Laravel

Mostly routing method accept a URL/URI and a Controller/Action or a Closure that return a value or not its depend on you 😂. Let check a simple example

PHPCopy
// routes/web.php

Route::get('/test', function () {
    return 'Hello Laravel';
});

If you want to pass a controller action/method just replace with Closure.

PHPCopy
// routes/web.php

Route::get('/test', [App\Http\Controllers\TestController::class, 'index']);

In Laravel you can easily respond mostly used HTTP verb like, GET, POST, PUT, PATCH, DELETE, and OPTIONS.

Facades in Laravel

PHPCopy
Route::get($url, $closure);
Route::post($url, $closure);

Route::put($url, $closure);
Route::patch($url, $closure);

Route::delete($url, $closure);

Route::options($url, $closure);

Note:

If you are using http verb like POST, PUT, DELETE, PATCH you need to pass csrf_token other wise it will return page expired error with 419 status code.

If you want get and post call same method of a controller or Closure you just use match() method that accept a array of HTTP verb or you want to match all HTTP verb then you can call any() method. Check the example.

Plain TextCopy
Route::match(['get', 'post'],  '/',  function () {
    // match get and post HTTP verb and return data from here
});

Route::any('/', function () {
      // match all HTTP verb and return data from here
});  

Redirection

If you want to redirect any routes from your current existing route its very simple to do in laravel. In Laravel two method which use 301 and 302 redirection status code. If you want to learn more about status check this article – HTTP Status Codes

PHPCopy
// this will redirect with 302 status code
Route::redirect('/here', '/there');


// this we redirect with 301 Status code
Route::permanentRedirect('/here', '/there');

Pass Views Direct to Routes

Sometime we don’t want to make a controller for routes for example if we have contact us and about us page we don’t need to create a controller for them so we can use view() method directly without making controller.

PHPCopy
Route::view('/test', 'test-view'); // 2nd argument is from resources/view/test-view.blade.php 

Route::view('/test', 'test-view', ['name' => 'Laravel']); // 3rd argument you can pass for extra value pass to view.

Routes Parameters

With Big project you need some dynamic route matching so you need a extra dynamic parameter to pass with route where that match and return result.

PHPCopy
// Here you need to pass id and use $id in your closure or controller method. this is required Parameter
Route::get('/book/{id}', function ($id) {
    return 'Book : '.$id; 
});


// Optional Parameter
Route::get('/book/{id?}', function ($id = null) {
    return 'Book : '.$id; 
});

You can use regular expression constraint where if that not match with desired one it will automatically throw an 404 error.

PHPCopy
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]+']);



// some predefined regular expression methods

Route::get('/user/{id}/{name}', function ($id, $name) {
    //
})->whereNumber('id')->whereAlpha('name');

Route::get('/user/{name}', function ($name) {
    //
})->whereAlphaNumeric('name');

Route::get('/user/{id}', function ($id) {
    //
})->whereUuid('id');

Advance Routing

Advance routing is nothing but some extra and less used methods that make life easier.

Facades in Laravel

Route Grouping

If you want share some additional attributes like prefix, routes names and middleware with more than one routes you can use Route’s group method that help and save you from duplicate code.

PHPCopy
// both method use two middleware
Route::middleware(['auth', 'subscribed_user'])->group(function () {
    Route::get('/', function () {
       //
    });

    Route::get('/user/profile', function () {
         /
    });
});

//you can use like this too
Route::group(['middleware'=> ['auth', 'subscribed_user']], function () {
    Route::get('/', function () {
       //
    });

    Route::get('/user/profile', function () {
         /
    });
});

Subdomain

If you want to handle request from subdomain you can use domain method but be aware while using subdomain routing. It should be used before grouping the routes.

PHPCopy
Route::domain('{test}.dumpcoder.com')->group(function () {
    Route::get('book/{id}', function ($test, $id) {
        //
    });
});

Route Binding

It is one of the most powerful thing in laravel that you not need to find your record every time via model. The Model Binding help to find record and return if exist other wise return 404 Error.

PHPCopy
// mostly beginner follow

Route::get('/users/{id}', function ( $user_id) {
    $user = App\Models\User::findOrFail($user_id);
    return $user->name;
});


// now use this ==== more cleaner code
Route::get('/users/{user}', function (App\Models\User $user) {
    return $user->name;
});

//customize key
Route::get('/books/{book:slug}', function (App\Models\Book $book) {
    return $book->title;
});

Resources Routes

Resources routes help you to write less code. For example If you have a CRUD operation you will need at least 6 method for all records, single records, create record route, store record route, edit single record route, update that single record route and last one for delete record but thanks to laravel you can do all in just one line –

PHPCopy
Route::resource('books', 'BookController'); # make sure you have index, show, create, store, edit, update and delete  === same name method other wise you need to tell laravel about each method

// you can also use api resource if you making apis

Route::apiResource('books', 'BookController');  # need index, show, store, update and delete method

Nested Resources Routes

Sometime its can be requirement that you need a nested routes.

PHPCopy
Route::resource('books.reviews', 'BookReviewController');
// URL will like - books/{books}/reviews/{reviews}

Multiple Routes in Single Resource Method

If you want more cleaner code you can use multiple resource routes in single resource method –

PHPCopy
Route::resources([
    'books' => App\Http\Controllers\BookController::class,
    'authors' => App\Http\Controllers\AuthorController::class,
]);

Route::apiResources([
      'books' => App\Http\Controllers\BookController::class,
      'authors' => App\Http\Controllers\AuthorController::class,
])

Conclusion

This is what you need to know about routing in laravel. Hope you get the point so make some awesome things with laravel. I will meet you in new guide.

Leave a Comment