PHP Development | Tutorial 8 | Laravel Routing & Middleware

by | Oct 3, 2025 | PHP Development, Web App Development | 0 comments

Every web application needs a way to map URLs to functionality. In Laravel, this is handled by the routing system. Whether it’s rendering a view, fetching data from a database, or returning a JSON API response, Laravel Routing & Middleware make it simple.

On top of routes, Laravel introduces middleware—powerful filters that sit between the request and response. Middleware handles tasks like authentication, logging, CSRF protection, and role checks without cluttering your controllers.

For interview prep, understanding routing basics, middleware roles, and real-world use cases is essential.

Routing in Laravel

1. Basic Routes

// routes/web.php
Route::get('/', function () {
    return view('welcome');
});

Route::get('/hello', function () {
    return "Hello, Laravel!";
});

👉 When a user visits /hello, Laravel executes the closure and returns the response.

2. Routes with Parameters

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

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

3. Named Routes

Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');

// Generate URL
$url = route('dashboard');

👉 Named routes are useful for URL generation and redirection.

4. Route Groups

Route::prefix('admin')->middleware('auth')->group(function () {
    Route::get('/users', [AdminController::class, 'users']);
    Route::get('/settings', [AdminController::class, 'settings']);
});

👉 Now /admin/users and /admin/settings are protected by the auth middleware.

5. API Routes

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

👉 API routes are stateless by default and often return JSON responses.

Middleware in Laravel

Middleware acts like a layered filter system around routes.

Example: Authentication Middleware

class Authenticate {
    public function handle($request, Closure $next) {
        if (!auth()->check()) {
            return redirect('login');
        }
        return $next($request);
    }
}

👉 Middleware checks conditions before passing the request to the controller.

Common Built-in Middleware in Laravel

  • auth → Ensures user is logged in.
  • guest → Restricts routes to non-logged-in users.
  • verified → Ensures user’s email is verified.
  • throttle → Rate limiting for APIs.
  • csrf → Prevents cross-site request forgery.

Registering Middleware

Global Middleware → Runs on every request (app/Http/Kernel.php).

Route Middleware → Applied to specific routes.

Route::get('/profile', function () {
    return "Profile Page";
})->middleware('auth');

Real-World Use Cases

  • Web Apps → Use auth middleware to protect dashboards.
  • APIs → Use throttle:60,1 to limit requests (60 per minute).
  • Role-based Apps → Custom middleware like isAdmin to restrict access.
  • Logging & Auditing → Middleware to log every request for compliance.

Common Beginner Mistakes

  • Forgetting to register custom middleware in Kernel.php.
  • Using routes in web.php for APIs (should use api.php).
  • Placing heavy logic in middleware (better to keep it lightweight).
  • Not naming routes, making redirection harder to manage.

Sample Interview Questions & Answers

Q: What is the difference between web.php and api.php routes in Laravel?
A: web.php routes use session state and CSRF protection (for web apps). api.php routes are stateless and optimized for APIs.

Q: What is middleware in Laravel?
A: Middleware is a filter that inspects or modifies requests before passing them to controllers.

Q: Can you give an example of middleware usage?
A: The auth middleware ensures that only logged-in users can access a route like /dashboard.

Q: How do you create custom middleware in Laravel?

php artisan make:middleware CheckRole

Q: What’s the difference between global middleware and route middleware?
A: Global middleware applies to all requests, while route middleware applies only to specific routes or groups.

Q: How does Laravel handle rate limiting in APIs?
A: Using the throttle middleware (e.g., throttle:60,1 for 60 requests per minute).

Mini Project Idea

👉 Build a Blog with Public & Admin Routes:

  • Public routes (/posts) visible to everyone.
  • Admin routes (/admin/posts) protected by auth + isAdmin middleware.
  • Demonstrate route groups, named routes, and middleware in action.

Closing Note

Laravel’s routing and middleware system makes it easy to build structured, secure, and scalable applications. Once you master routes and middleware, you can create APIs, dashboards, and role-based applications with confidence.

Master PHP Development

Build your PHP expertise with these essential guides:

PHP Error Handling and Debugging
Debug like a pro → Learn advanced techniques to catch and fix errors efficiently

PHP Sessions and Cookies Tutorial
Master user data management → Handle authentication, state, and user preferences

Why Choose Laravel?
Ready for frameworks? → Discover why Laravel is the top choice for modern PHP developers

Laravel MVC Architecture
Build scalable applications → Understand Models, Views, Controllers, and architectural patterns


Pro Tip: Follow this learning path for the best results: Start with PHP BasicsBust the MythsMaster OOP ConceptsLearn Error Handling & SessionsGraduate to Laravel → Master Laravel Routing & Middleware!

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *