Laravel provides us with a convenient way of routing. We can easily accept a URI with closure in Laravel routing. The router allows you to register routes that respond to any HTTP request. The available routes in Laravel 9 are given below:

laravel-9-routing-example

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);

 

Here get, post, put, patch, delete and options are the request type. The most basic Laravel routes accept a URI and closure like the below:

routes/web.php

<?php

use Illuminate\Support\Facades\Route;
 
Route::get('/greeting', function () {
    return 'Hello World';
});

 

Now if you visit the below URL, then you will see the Hello World output.

 

URL
https://127.0.0.1:8000/greeting

 

Define route with controller and method

Laravel gives us a convenient way of defining routes with a controller and a method. See the below example of defining a route with a controller:

routes/web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\TestController;
 
Route::get('/user', [TestController::class, 'index']);

 

Look at this route, here /user is the URI and UserController is the controller and index is the method of this controller. Now define the index method in your controller like:

App\Http\Controllers\TestController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TestController extends Controller
{
    public function index()
    {
        return "Hello World";
    }
}

 

Now if you visit the /user URL then you will see the same output as before.

 

Category : #laravel

Tags : #laravel , #laravel routing