How to Define Routes in Laravel

Updated: January 15, 2024 By: Guest Contributor Post a comment

Introduction

Laravel is a robust PHP framework designed for the development of web applications following the model-view-controller (MVC) architectural pattern. Routing in Laravel is exceptionally powerful and provides a smooth interface for creating behavior based on HTTP requests to an application. In this tutorial, we’ll guide you through defining routes in Laravel from the basic to advanced practices, complete with code examples and explanations.

Understanding Laravel’s Routing

The basics of routing in Laravel are simple. All Laravel routes are defined in your route files, which are located in the routes folder. There are various route files for different purposes, such as web.php, api.php, console.php, and channels.php. For now, we’ll focus on web routes.

Defining Basic Routes

The simplest way to define a route is to add a closure to the web.php file. Here’s a basic GET route:

Route::get('/', function () {    return 'Welcome to my Laravel app!';});

This route responds to a request to the application’s root URL with the text “Welcome to my Laravel app!”. You can define routes for various HTTP verbs like POST, PUT, DELETE, and more in a similar fashion.

Controllers

Instead of using closures, you can associate a route with a controller action. Let’s assume we have a PageController with a method about:

Route::get('/about', 'PageController@about');

Here we’re telling Laravel to handle GET requests to /about by calling the about method on PageController.

Route Parameters

Routes can also be defined to contain parameters, which can be passed to the controller:

Route::get('/posts/{post}', 'PostController@show');

The {post} placeholder indicates a route parameter that will be supplied to the show method of PostController.

Named Routes

Named routes make it more convenient to generate URLs or redirects. Here’s how you name a route:

Route::get('/contact', 'ContactController@show')->name('contact');

Then, you can refer to this route by its name using the route function:

url(route('contact'));

Middleware

Middleware can be applied to routes to filter HTTP requests entering your application. For example, to apply the auth middleware to a route:

Route::get('/profile', 'UserController@show')->middleware('auth');

This makes sure that users must be authenticated to access the /profile route.

Advanced Routing

Route Groups

Route groups allow you to share route attributes, such as middleware or namespace, across many routes without redundancy:

Route::middleware(['auth'])->group(function () {    Route::get('/dashboard', 'DashboardController@index');    Route::get('/account', 'AccountController@index');});

Route Model Binding

With route model binding, you can automatically resolve model instances by their ID. Laravel magically injects the corresponding model instance directly:

Route::get('/posts/{post}', function (App\Post $post) {    return view('post.show', ['post' => $post]);});

Note that you have to use type-hinting for the model in your route’s closure or controller method, and Laravel does the rest.

Subdomain Routing

Laravel allows you to easily handle routes on subdomains. You can define a route group with a domain attribute:

Route::domain('{account}.myapp.com')->group(function () {    Route::get('user/{id}', function ($account, $id) {        // ...    });});

This routes the requests to a subdomain to corresponding closures or controller actions, with variables for the account and ID being made available.

Rate Limiting

Laravel’s Router includes functionalities to limit the rate of incoming requests. You can specify the amount and time period for requests:

Route::middleware('auth:api', 'throttle:60,1')->group(function () {    // API routes that are rate-limited});

Resource Controllers

Resource controllers make it easy to handle CRUD operations for a resource. You can generate a resource controller using Artisan:

php artisan make:controller PhotoController --resource

Then, you can register a resourceful route in your routes/web.php:

Route::resource('photos', 'PhotoController');

This creates all the necessary routes for your resource in a single command.

Conclusion

Laravel’s routing system is intuitive and flexible, enabling you to define routes that respond to any HTTP verb. Clear conventions, middleware integration, route grouping, subdomain routing, and rate limiting provide a powerful toolset for developers. Understanding and leveraging these features will significantly enhance the functionality and security of your Laravel applications.