Different mechanism and techniques to use routes in Laravel


Hello Artisan, Route and URI paths are the most fundamental and important components of every web app. Every technology has some route-handling mechanisms. Today in this article I will let you know different mechanisms and techniques of Laravel routes.

In Laravel all routes are defined in web.php and api.php in routes directory.

Web routes offer features like session state and CSRF protection, whereas api routes are stateless and belong to the api middleware group. This is the primary difference between web and api routes.

Let’s start with Laravel’s available routing methods. Laravel offers the following standard routing methods.

Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);

In addition to this, Laravel routing has the anymatch, and redirect methods.

Below are the different ways to define and improve route usage in Laravel

1.Simple View route without controller

If you don’t need any logic processing then you can use route as below,

Route::get('/session-time', function () {
   return config('session.lifetime'); // return session lifetime
});
Route::get('/', function () {
   return view('welcome'); // return blade view directly
});

2. Define route using controller method

When you have to process and implement logic then you can use route like below,

Route::get('/users', 'UserController@index');
Alternatively you can define it as below.
Route::get('/users', [UserController::class, 'index']);

3. Dependency Injection in routes

Route::get('/get-ip', function (Request $request) {
    return $request->ip();
});

4. View Routes

When you need to return response from blade file directly then you can use view routes.

Route::view('/welcome', 'welcome');// pass parameter
Route::view('/welcome', 'welcome', ['name' => 'Taylor']);

5. Redirect Routes

If you are defining a route that redirects to another URI, you may use the Route::redirect method. By default, Route::redirect returns a 302 status code. You may customize the status code using the optional third parameter:

Route::redirect('/users', '/new-users');
Route::redirect('/users', '/new-users', 301);

6. Parameterized Routes

Sometimes you will need to capture segments of the URI within your route. For example, you may need to capture a user’s ID from the URL. You may do so by defining route parameters:

Route::get('/user/{id}', function ($id) {
    return 'User '.$id;
});
Route::get('/posts/{post}/comments/{comment}', function ($postId, $commentId) {
    //
});

7. Optional Parameterized Routes

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

8. Controller Route (New in Laravel 9)

If a group of routes all utilize the same controller, you may use the controller method to define the common controller for all of the routes within the group.

Route::controller(OrderController::class)->group(function () {
    Route::get('/orders/{id}', 'show');
    Route::post('/orders', 'store');
});

9. Named Routes

You can assign name to any route, main benefits of named routes is you can change url pattern conveniently anytime, keep in mind one thing, Route names should always be unique. Check below example,

Route::get('/users/profile/1', function () {
    //
})->name('profile'); 
// you can also use user.profile as name, or whatever you want.

10. Middleware Route

When you wish to restrict user access with a specific middleware, you can attach middleware directly to routes. check below example,

Route::get('/users', function () {
    //
})->middleware(['auth', 'master-admin']);

11.  Route Groups

By using route group you can share basic route attributes such as middleware, prefix, naming, etc check below examples,

Route::middleware(['auth', 'master-admin'])->group(function () {
    Route::get('/users', function () {
       // return list of users
    })->name('users.index');
    
    Route::get('/users/profile/1', function () {
       // return user Profile
    })->name('users.profile');
});
More attractive way to improve above route is,
Route::middleware(['auth', 'master-admin'])->prefix('users')->name('users.')->group(function () {
    Route::get('/', function () {
       // return list of users
    })->name('index');
    
    Route::get('/profile/1', function () {
       // return user Profile
    })->name('profile');
});

Both of above example will generate exact same routes.

12. Resource Routes

It generates all routes which is required for CRUD operations,

Route::resource('users', 'UsersController'); 
it will generate below routes
   Method        Path                     Action    Name
   GET           /users                   index     users.index
   GET           /users/create            create    users.create
   POST          /users                   store     users.store
   GET           /users/{user}            show      users.show
   GET           /users/{user}/edit       edit      users.edit
   PUT|PATCH     /users/{user}            update    users.update
   DELETE        /users/{user}            destroy   users.destroy
// you can do like below also
Route::resources([
   'users' => UserController::class
   'books' => BookController::class
]);
Route::apiResource('books', BookController::class);
this will not create create and edit form route as api doesn't require visual forms

13. Fallback Routes

When any incoming request doesn’t match any routes then this route will be executed,

Route::fallback(function () {
    // return 404 or some error
});

14. Implicit Route Model Binding

use App\Models\User;
Route::get('/users/{user}', function (User $user) {
    return $user->email;
});

You can dig deeper about Route in Laravel in official documents.



Share this post