Laravel Routing: A Beginner’s Guide to Building Powerful Web Applications

Viraj Madhushan
5 min readMay 5, 2023

--

Laravel routing is a powerful feature that allows you to define how your application responds to incoming requests. In this blog post, we’ll explore how to create and manage routes in Laravel.

To begin, let’s create a new Laravel app using Composer. I’m naming my app routing-blog. Before getting started, make sure you have Composer installed on your PC. You can find the system requirements and installation instructions on the official Composer website at 👉 https://getcomposer.org/doc/00-intro.md#system-requirements .

composer create-project laravel/laravel routing-blog

Next, navigate to the project folder you just created and open it using your favorite IDE. In my case, I’m using VS Code. Once you have it open, you’ll see a “routes” folder in the root directory of the project. Inside that folder, there are four PHP files: api.php, channels.php, console.php, and web.php.

Default folder structure and routes location

These files are separated based on their purpose, and Laravel provides a clear and organized way to manage your application’s routes. This makes it easier to maintain and update your routes as your application grows and evolves.

Let’s talk a little bit more about these files.

api.php

This file contains routes that are meant to be accessed by external systems, such as mobile applications or other web services. These routes usually return JSON or XML responses.

Default view of api.php file

channels.php

This file contains routes that are used for real-time messaging or broadcasting through channels. These routes are typically used with Laravel’s broadcasting system, which allows your application to broadcast events and messages to connected clients.

Default view of channels.php file

console.php

This file contains routes that are used for interacting with the command line interface (CLI). These routes are used to define custom commands and tasks that can be executed through the CLI.

Default view of console.php file

web.php

This file contains routes that are typically used for web applications. These routes are meant to be accessed through a web browser and usually return views or HTML responses.

Default view of web.php file

Basically, we will focus only on the web.php routes for now. If you want to learn more advanced details about Laravel routing, you can explore the other routing files as well.

Basic of Laravel Route

Laravel's route mainly contain 3 parts.

Basic parts of Laravel route
  1. Method — The HTTP verb or request method (e.g., GET, POST, PUT, DELETE) that the route should respond to.
  2. URI — The uniform resource identifier (URI) or path that the route should match. This is the part of the URL after the domain name.
  3. Function — The controller method or closure that should be executed when the route is matched. This defines the logic that should be performed when the route is accessed by a client.

Together, these three parts define how your application should respond to incoming requests. By defining routes in your Laravel application, you can create a clear and organized structure for handling client requests and executing the corresponding business logic.

Available Router Methods

There are 6 router methods in Laravel. They are get, post, put, patch, delete, options. Sometimes you may be wanted to use multiple methods to the same URI. Then you can use match or any 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);
Route::match(['get', 'post'], '/', function () {});

Route::any('/', function () {});

Route parameters in Laravel

Laravel also allows you to define dynamic routes using route parameters. Route parameters are placeholders in the URL that capture specific values and pass them to the closure or controller action.

For example, to define a route that captures a user’s ID from the URL, you would use the following code:

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

This creates a route for URLs that match the pattern /users/{id}, where {id} is a placeholder for a user ID. When a user navigates to a URL that matches this pattern, the closure function is executed and the value of the id parameter is passed as an argument.

Optional Parameters

In Laravel, we can use optional parameters by adding a question mark (?) after the parameter name.

Route::get('/users/{name?}', function ($id, string $name = 'Jhon') {
return "User Name: " . $name;
});

This creates a route for URLs that match the pattern /users/{name}, but name is optional parameter. If we not pass the name paramaeter it will take default parameter name as “ Jhon ”

Route groups in Laravel

In Laravel, route groups allow you to group related routes together and apply middleware or other settings to them. To define a route group, you can use the Route::group() method.

Route::group(['middleware' => 'auth'], function () {
Route::get('/dashboard', function () {
return view('dashboard');
});
Route::get('/profile', function () {
return view('profile');
});
});

This creates a group of routes that require the user to be authenticated. The middleware is applied to the entire group, so any routes within the group will require authentication.

Best way to create a route?

Usually, creating functions inside the web.php file is not considered a best practice as it can complicate your route file. Instead, you should create the functions inside a controller and call them in your router.
Here is the controller

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
public function getUser($id)
{
// rest of your code
}

public function addUser(Request $request)
{
// rest of your code
}
}

And we can use that function in our route file like this

<?php

use App\Http\Controllers\UserController;

Route::get('/users/{id}', [UserController::class, 'getUser']);
Route::post('/users/add-user', [UserController::class, 'addUser']);

To make the route file more clear and readable, we can use the controller method to define a common controller for all of the routes within a group.

<?php

use App\Http\Controllers\UserController;

Route::controller(UserController::class)->group(function () {
Route::get('/users/{id}', 'getUser');
Route::post('/users/add-user', 'addUser');
});

Conclusion

Laravel routing is a powerful feature that allows you to define how your application responds to incoming requests. With Laravel routes, you can create basic routes, dynamic routes with parameters, and route groups with middleware and other settings. By mastering Laravel routing, you’ll be able to create flexible and robust applications with ease.

--

--

Viraj Madhushan

Passionate learner of AI and Robotics. Always exploring new technologies to stay ahead of emerging trends. Hiking and reading enthusiast.