In Laravel, a route is a way to define how your application responds to various HTTP requests. Routes allow you to map URLs to specific actions in your application, typically handled by controller methods. Laravel provides a simple and expressive way to define routes, which can be found in the routes/web.php file for web routes or routes/api.php for API routes.
Types of Routes
- Basic Routing:
- You can define a simple route that maps a URL to a closure function or a controller method.
// In routes/web.php// Route to a closureRoute::get('/hello', function () { return 'Hello, World!';});// Route to a controller methodRoute::get('/user/{id}', 'UserController@show');
2. Route Parameters:
- Routes can accept parameters, which can be passed to the route’s action.
// Required parameterRoute::get('/user/{id}', function ($id) { return 'User '.$id;});// Optional parameterRoute::get('/user/{name?}', function ($name = 'Guest') { return 'User '.$name;});
3. Named Routes:
- You can name your routes to make it easier to generate URLs or redirects for a specific route.
Route::get('/user/profile', 'UserProfileController@show')->name('profile');// Generating a URL for the named route$url = route('profile');// Redirecting to the named routereturn redirect()->route('profile');
4. Route Groups:
- You can group routes to share route attributes, such as middleware or namespace.
Route::middleware(['auth'])->group(function () { Route::get('/dashboard', 'DashboardController@index'); Route::get('/account', 'AccountController@index');});