Routing in Laravel

πŸ“˜ Laravel πŸ‘ 59 views πŸ“… Dec 22, 2025
⏱ Estimated reading time: 2 min

Routing in Laravel defines how an application responds to incoming HTTP requests. It maps URLs to specific actions such as returning a view, executing a controller method, or processing data. Laravel’s routing system is simple, expressive, and powerful.


1. Route Files in Laravel

Laravel routes are defined inside the routes/ directory:

  • web.php – Routes for web applications (supports sessions, cookies, CSRF)

  • api.php – Routes for APIs (stateless, prefixed with /api)

  • console.php – Artisan command routes

  • channels.php – Broadcasting channels

Most applications primarily use web.php and api.php.


2. Basic Routing

A basic route returns a response when a URL is accessed:

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

Here:

  • get is the HTTP method

  • / is the URL

  • The function returns a response


3. Routing to Views

Routes can directly return views:

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

The view file must exist in resources/views/about.blade.php.


4. Routing to Controllers

Controllers keep logic organized:

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

This route calls the index method of UserController.


5. Route Parameters

Routes can accept parameters:

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

Optional parameters:

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

6. Named Routes

Named routes make URL generation easier:

Route::get('/profile', [ProfileController::class, 'show'])->name('profile');

Usage:

route('profile');

7. Route Groups

Route groups help organize routes:

Middleware Group

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

Prefix Group

Route::prefix('admin')->group(function () { Route::get('/users', function () { return 'Admin Users'; }); });

8. Resource Routes

Resource routes automatically create CRUD routes:

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

This creates routes for:

  • index

  • create

  • store

  • show

  • edit

  • update

  • destroy


9. API Routing

API routes are defined in api.php:

Route::get('/users', function () { return response()->json(['users' => []]); });

These routes are stateless and automatically prefixed with /api.


10. Route Caching

For better performance, Laravel allows route caching:

php artisan route:cache

To clear cache:

php artisan route:clear

Conclusion

Laravel routing provides a clean and flexible way to handle HTTP requests. With features like route parameters, named routes, middleware, and resource routing, Laravel makes building both web and API applications efficient and well-structured.


πŸ”’ Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes