Press ESC to close

Laravel Routes

  • May 04, 2024
  • 2 minutes read
  • 156 Views

In Laravel, you can define several types of routes based on the HTTP methods and the purpose of the route.

All the application routes are registered within the routes/web.php file.

route_ss

 web.php file you can see the sample route for the welcome page, as shown in the screenshot below.

<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
   return view('welcome');
});

Route types

  • Basic Route
  • Route Parameters
  • Named Routes
  • Route Groups
  • Resource Routes
  • API Resource Routes

Basic Route

They respond to HTTP requests like GET, POST, PUT, DELETE, etc.

The two most common HTTP methods are: GET and POST.

The routes map the URL to a specific controller method or closure function. For example:

// GET route
Route::get('URL',['ControllerName'=>'ControllerMethod']);

// POST route
Route::post('URL',['ControllerName'=>'ControllerMethod']);

Route Parameters

  • You can define route parameters to capture parts of the URL and pass them as arguments to your controller methods.
  • Parameters are enclosed in curly braces { } . For example:
Route::get('/test/{id}', ['ControllerName'=>'ControllerMethod']);
  • You can also pass multiple parameters. For example:
Route::get('/test/{id}/edit/{name}', ['ControllerName'=>'ControllerMethod']);

Named Routes

  • Named routes allow you to assign a unique name to a route. 
  • This makes it easier to reference the route in your application’s code.
  • You can use the name method to name a route. For example:
Route::get('/test, ['ControllerName'=>'ControllerMethod'])->name('test');

Route Groups

  • Route groups allow you to apply common attributes, such as middleware or a prefix, to a group of routes.
  • This helps keep your routes organized and makes it easier to maintain the application. For example:
Route::prefix('admin')->middleware('auth')->group(function () {
   // Admin routes go here...
});

Resource Routes

  • Resource routes automatically generate routes for common CRUD operations (Create, Store, Update, Show, Edit, Delete) For example:
Route::resource('posts', 'PostController');

Leave a comment

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