How do you define routes in Laravel?
In Laravel, routes define how the application responds to various HTTP requests. You can define routes in several ways, primarily in the route files located in the routes
directory.
Here are the main methods to define routes in Laravel:
-
Basic Routes: Define a route that responds to a specific URL and HTTP method. For example:
Route::get('/home', function () { return 'Welcome to the home page!'; });
This defines a GET route for the
/home
URL that returns a simple string. -
Route with Controller: Routes can be directed to a controller method:
Route::get('/users', [UserController::class, 'index']);
This routes the GET request for
/users
to theindex
method ofUserController
. -
Route with Parameters: Routes can include parameters that are passed to the controller or route closure:
Route::get('/user/{id}', function ($id) { return 'User ID: ' . $id; });
Here,
{id}
is a parameter that can be accessed within the closure. -
Named Routes: You can give routes a name to make generating URLs easier:
Route::get('/profile', [UserController::class, 'profile'])->name('profile');
You can generate a URL or redirect to this route using the name:
$url = route('profile'); return redirect()->route('profile');
-
Route Groups: Group routes that share attributes, such as middleware or namespaces:
Route::middleware('auth')->group(function () { Route::get('/dashboard', function () { return 'Dashboard'; }); Route::get('/settings', function () { return 'Settings'; }); });
-
Route Prefixes and Subdomains: Apply prefixes or subdomains to routes in a group:
Route::prefix('admin')->group(function () { Route::get('/dashboard', function () { return 'Admin Dashboard'; }); });
Or, use subdomains:
Route::domain('admin.example.com')->group(function () { Route::get('/', function () { return 'Admin Home'; }); });
-
Resource Routes: Automatically create routes for a controller's CRUD operations:
Route::resource('posts', PostController::class);
This creates routes for
index
,create
,store
,show
,edit
,update
, anddestroy
actions inPostController
.
These methods are defined in the route files typically found in the routes
directory, such as web.php
for web routes and api.php
for API routes.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.