Our Work
200+ Enterprises across globally trust KTree for their Web & Mobile application Development needs.See What We Do
Updated today
You can refer the code here :https://github.com/KtreeOpenSource/Laravel_Middleware
Here we are going to learn how to add a route middleware in laravel.
Middleware act as a firewall between requests and response
Often we need to check if request are meeting certain conditions in our application,if not we need to make them unauthorized.
Execute the artisan command php artisan make:middleware CheckRequest
This creates a file at the path :app/Http/Middleware/CheckRequest.php.Add the following in the CheckRequest.php
Here let's check if the request is having a header parameter say ‘ip’ of which some values are already configured in the application.
$myIps = ['10.0.3.59']; //the ips or domains we are allowing
If the parameter ip coming from the request header doesn't match with the existing values in the application we need to throw unauthorized error.
if(in_array($requestIp, $myIps))//checking if the requests are coming from the known ips or domain {
return $next($request);
}
<?php
namespace App\Http\Middleware;
use Closure;
class CheckRequest
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$myIps = ['10.0.3.59']; //the ips or domains we are allowing
// info([$request->manager1,$request->manager2]);
//info($request->header('ip'));
$requestIp = $request->header('ip');
if(in_array($requestIp, $myIps))//checking if the requests are coming from the known ips or domain {
return $next($request);
}
return response()->json(['status' => 401]);//throw unauthorized
}
}
path:routes/web.php
Route::group(['prefix' => 'operations','middleware' => CheckRequest::class], function()
{
Route::get('/test/{manager1}/{manager2?}', function ($manager1,$manager2 = null) {
return $manager1.$manager2;
});
});
Please Contact us if you have any Laravel Implementation requirements. Hire dedicated Laravel developers or Laravel Development services from KTree. KTree is Best offshore Laravel development company with extensive experience in building Laravel web applications and Laravel Plugins.
Request For Quote