Laravel - Middleware

version : Laravel 10
Post Time : 05-07-2024

Laravel - Middleware

install laravel


         -   composer create-project --prefer-dist laravel/laravel:^10.0 laravel_demo


To get location from IP Address


          -   composer require stevebauman/location  


Create Middleware


          -   php artisan make:middleware getUserCountry



app/Http/Middleware/GetUserCountry.php

                                      
                                        

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

use Illuminate\Support\Facades\Session;
use Location;

class GetUserCountry
{
   /**
    * Handle an incoming request.
    *
    * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
    */
   public function handle(Request $request, Closure $next): Response
   {

       $position = Location::get($request->ip());
       $country = $position ? $position->countryName : 'Unknown';

       // Store the country in the session
       Session::put('country', $country);
       
       return $next($request);
   }
}

Register middleware in app/Http/Kernel.php

We can Register middleware  as per our requirement for all routes 'globally' , for 'web' or 'api' routes , or for specific 'route group', Here we did it for specific route group.

                                      
                                        

//To Apply for specific route group

protected $middlewareAliases = [
           ...
           ...

       /*-------Custom Middleware----*/
       'userCountry' => \App\Http\Middleware\GetUserCountry::class,
   ];

//To Apply Middleware for all Routes Globally

protected $middleware = [
       ...
       ...

   /*-------Custom Middleware----*/
   \App\Http\Middleware\GetUserCountry::class,
];

//To Apply middleware for all WEB route route we can register in web OR To Apply for API Routes register in API 

protected $middlewareGroups = [
   'web' => [
           ...
           ...
       
       /*-------Custom Middleware----*/
       \App\Http\Middleware\GetUserCountry::class,
   ],

   'api' => [
       ...
       ...

   ],
];

Create DemoController Controller  :


          -  php artisan make:controller DemoController


 app/Http/Controllers/DemoController.php

                                      
                                        

<<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Session;

class DemoController extends Controller
{
   public function getProductList(Request $request)
   {
       echo $countryName =  Session::get('country');
   }
  
}

routes/web.php

                                      
                                        

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\DemoController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/
Route::get('/', function () {
   return view('welcome');
});

/*---- for Route Group ----*/
Route::middleware(['userCountry'])->group(function () {
   Route::get('/get-product-list', [DemoController::class, 'getProductList'])->name('getProductList');
});
/*---- For Global middleware  OR Web and Api Route middleware ----*/
Route::get('/get-product-list', [DemoController::class, 'getProductList'])->name('getProductList');

Note :- In Local Machine it will return unknown , On server it will return country name