Laravel

Laravel is a powerful and popular PHP framework that simplifies and accelerates web application development. Its elegant syntax, robust features like Eloquent ORM, Blade templating, and built-in security tools help developers create efficient and scalable apps. With strong community support and extensive documentation, Laravel is an ideal choice for both novice and experienced developers

Laravel Routing Basics: Understanding web.php and api.php

15 May 2025 | Category:

Routing is a fundamental concept in Laravel, defining how HTTP requests are mapped to specific application logic, such as controllers or closures. Laravel’s routing system is simple yet powerful, enabling developers to create clean, organized, and maintainable URL structures. This SEO-friendly, plagiarism-free guide explains the basics of routing in Laravel, focusing on the web.php and api.php files, their purposes, and how to use them effectively. The explanation is based on Laravel 11 (as of May 2025) and is tailored for beginners and intermediate developers.


What is Routing in Laravel?

Routing in Laravel determines how an application responds to a client’s request to a specific URL (endpoint) and HTTP method (GET, POST, PUT, DELETE, etc.). Routes are defined in the routes/ directory, primarily in web.php for web interfaces and api.php for API endpoints. Each route maps a URL pattern to a controller method, a closure, or a view.

Key Features of Laravel Routing

  • Expressive Syntax: Define routes with clean, readable code.
  • Middleware Support: Apply middleware (e.g., authentication, CSRF protection) to routes.
  • Route Grouping: Organize routes with prefixes, middleware, or namespaces.
  • Named Routes: Assign names to routes for easy URL generation.
  • RESTful Routing: Simplify resource-based routing for CRUD operations.

The routes/ Directory

In a Laravel project, the routes/ directory contains the route definition files:

  • web.php: Defines routes for web interfaces, typically rendering views with session and CSRF protection.
  • api.php: Defines stateless API routes, optimized for JSON responses.
  • console.php: Registers Artisan commands (not related to HTTP routing).
  • channels.php: Configures broadcasting channels for real-time features.

This guide focuses on web.php and api.php, the primary files for handling HTTP requests.


1. Understanding web.php

The web.php file is used for routes that power web applications, such as those rendering HTML views (e.g., Blade templates). These routes are automatically applied with the web middleware group, which includes features like:

  • Session management.
  • CSRF protection for POST forms.
  • Cookie handling.

Basic Syntax

Routes in web.php are defined using the Route facade. Here’s a simple example:

use Illuminate\Support\Facades\Route;

Route::get('/welcome', function () {
    return view('welcome');
});
  • Route::get: Handles GET requests to the /welcome URL.
  • function () { ... }: A closure that returns the welcome.blade.php view.

Common Route Methods

Laravel supports various HTTP methods:

Route::get($uri, $callback);    // Handle GET requests
Route::post($uri, $callback);   // Handle POST requests
Route::put($uri, $callback);    // Handle PUT requests
Route::patch($uri, $callback);  // Handle PATCH requests
Route::delete($uri, $callback); // Handle DELETE requests
Route::options($uri, $callback); // Handle OPTIONS requests

Connecting to Controllers

Instead of closures, routes often map to controller methods for better organization:

use App\Http\Controllers\PostController;

Route::get('/posts', [PostController::class, 'index']);
  • [PostController::class, 'index']: Calls the index method in PostController.

Named Routes

Naming routes simplifies URL generation in views or redirects:

Route::get('/posts', [PostController::class, 'index'])->name('posts.index');

Use the name in Blade:

<a href="{{ route('posts.index') }}">View Posts</a>

Example web.php

Here’s a sample web.php file:

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;

Route::get('/', function () {
    return view('welcome');
});

Route::get('/posts', [PostController::class, 'index'])->name('posts.index');
Route::get('/posts/{id}', [PostController::class, 'show'])->name('posts.show');
Route::post('/posts', [PostController::class, 'store'])->name('posts.store');

Key Points

  • Middleware: The web middleware group is applied automatically, enabling sessions and CSRF tokens.
  • Use Case: Ideal for browser-accessible pages, such as dashboards, forms, or public websites.
  • CSRF Protection: POST, PUT, and DELETE routes require a CSRF token in forms:
  <form method="POST" action="/posts">
      @csrf
      <input type="text" name="title">
      <button type="submit">Submit</button>
  </form>

2. Understanding api.php

The api.php file is designed for stateless API routes, typically returning JSON responses for consumption by front-end frameworks (e.g., Vue, React) or mobile apps. These routes are applied with the api middleware group, which includes:

  • Throttling (rate limiting).
  • No session or CSRF protection (APIs are stateless).

Basic Syntax

Routes in api.php follow a similar syntax to web.php but are prefixed with /api/ by default:

use Illuminate\Support\Facades\Route;

Route::get('/users', function () {
    return response()->json(['users' => \App\Models\User::all()]);
});
  • Access this route at: your-domain.com/api/users.

Using Controllers

API routes often map to dedicated API controllers:

use App\Http\Controllers\Api\UserController;

Route::get('/users', [UserController::class, 'index']);

Resource Routes

Laravel’s resource routes simplify CRUD operations:

Route::resource('posts', PostController::class);

This generates seven RESTful routes (index, create, store, show, edit, update, destroy).

Authentication

API routes often use token-based authentication (e.g., Laravel Sanctum or Passport):

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Example api.php

Here’s a sample api.php file:

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Api\PostController;

Route::get('/posts', [PostController::class, 'index']);
Route::post('/posts', [PostController::class, 'store'])->middleware('auth:sanctum');
Route::get('/posts/{id}', [PostController::class, 'show']);

Key Points

  • Prefix: Routes are automatically prefixed with /api/ (configurable in RouteServiceProvider).
  • Stateless: No session or CSRF protection; use tokens or API keys for authentication.
  • Use Case: Ideal for building RESTful APIs or headless applications.
  • Rate Limiting: The api middleware includes throttling to prevent abuse.

Differences Between web.php and api.php

Featureweb.phpapi.php
PurposeWeb interfaces (HTML, views)APIs (JSON responses)
Middlewareweb (sessions, CSRF, cookies)api (throttling, no sessions)
URL PrefixNone (e.g., /posts)/api/ (e.g., /api/posts)
StateStateful (uses sessions)Stateless (no sessions)
AuthenticationSession-based (default)Token-based (e.g., Sanctum, Passport)
Typical ResponseHTML (Blade views)JSON

Advanced Routing Features

Route Parameters

Capture dynamic URL segments:

Route::get('/posts/{id}', function ($id) {
    return "Post ID: $id";
});

Optional parameters:

Route::get('/posts/{id?}', function ($id = null) {
    return $id ? "Post ID: $id" : "No ID provided";
});

Route Groups

Group routes with shared attributes (e.g., middleware, prefix):

Route::middleware('auth')->prefix('admin')->group(function () {
    Route::get('/dashboard', [AdminController::class, 'index']);
    Route::get('/settings', [AdminController::class, 'settings']);
});
  • Routes: /admin/dashboard, /admin/settings.
  • Middleware: auth ensures only authenticated users can access.

Route Caching

For performance, cache routes:

php artisan route:cache

Clear cache:

php artisan route:clear

Best Practices for Laravel Routing

  1. Use Named Routes: Simplify URL generation with route('name').
  2. Organize Controllers: Separate web and API controllers (e.g., App\Http\Controllers\Api\PostController).
  3. Apply Middleware: Use middleware for authentication, authorization, or input validation.
  4. Keep Routes Lean: Avoid complex logic in closures; use controllers instead.
  5. Secure APIs: Use Sanctum or Passport for API authentication and throttling.
  6. Follow REST Conventions: Use resource routes for consistent CRUD APIs.

Conclusion

Laravel’s routing system, centered around web.php and api.php, provides a flexible and intuitive way to handle HTTP requests. The web.php file is perfect for building web applications with views and sessions, while api.php is tailored for stateless APIs returning JSON. By mastering routing basics—such as defining routes, using controllers, and applying middleware—you can create clean, scalable, and maintainable Laravel applications.

Next Steps:

  • Create a new Laravel project: composer create-project laravel/laravel my-app.
  • Experiment with routes in web.php and api.php.
  • Explore middleware and resource routes in Laravel’s official documentation.

For further learning, join Laravel communities on platforms like X or dive into the official Laravel documentation. Happy routing!