Routing in Laravel
β± 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:
Here:
-
getis the HTTP method -
/is the URL -
The function returns a response
3. Routing to Views
Routes can directly return views:
The view file must exist in resources/views/about.blade.php.
4. Routing to Controllers
Controllers keep logic organized:
This route calls the index method of UserController.
5. Route Parameters
Routes can accept parameters:
Optional parameters:
6. Named Routes
Named routes make URL generation easier:
Usage:
7. Route Groups
Route groups help organize routes:
Middleware Group
Prefix Group
8. Resource Routes
Resource routes automatically create CRUD routes:
This creates routes for:
-
index
-
create
-
store
-
show
-
edit
-
update
-
destroy
9. API Routing
API routes are defined in api.php:
These routes are stateless and automatically prefixed with /api.
10. Route Caching
For better performance, Laravel allows route caching:
To clear cache:
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.
Register Now
Share this Post
β Back to Tutorials