Showing posts with label Http Middleware. Show all posts
Showing posts with label Http Middleware. Show all posts

Sunday, June 25, 2017

Laravel 5: Use of Laravel Middleware WEB | API | THROTTLE

You have to create a middleware first. Create a php file named "ApiFilter.php" in "app/Http/Middleware" folder with following contents:


<?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request as HttpRequest;

class ApiFilter
{
    protected $auth;

    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    public function handle(HttpRequest $request, Closure $closure)
    {
        if ($this->auth->guest()) {
            if ($request->ajax()) {
                return response('Unauthorized.', 401);
            }
            else {
                return redirect()->guest('login');
            }
        }
        return $closure($request);
    }
}


Now you have to register this middleware to your project. Need to open "App\Http\Kernel.php" file. If you want to register this middleware for global scope then you have to add the below line as follows:


protected $middleware = [
    \App\Http\Middleware\ApiFilter::class
];


So when you browse any url in your project scope, this middleware can handle them.

But if you want to the middleware for specific area you have to add the middleware to "$middlewareGroups" as follows:


protected $middlewareGroups = [
    'web' => [
        .....
    ],

    'api' => [
        'throttle:3,1',
        \App\Http\Middleware\ApiFilter::class
    ],
];


Now add the following lines to "app\Http\routes.php":


Route::group(["middleware" => "api", "prefix" => "api"], function() {
    Route::get('action_name', 'ApiController@action_name');
});


If you browse "www.domain.com/api/action_name" it will pass through ApiFilter middleware bacause of prefix "api" used. But if you only browse "www.domain.com/action_name" it will pass through another middleware.



These middleware may be assigned to groups or used individually


protected $routeMiddleware = [
    'my_middleware' => \App\Http\Middleware\Authenticate::class
];

And can be used as below:

Route::group(['middleware' => 'my_middleware'], function() {
    Route::get('landing-page', 'MyController@landingPage');
});


We can use "throttle" which will restrict request overloading. Here we used "throttle:3,1" means per minute 3 request can be granted, if more request send request rejected as below image:

We need to add below line to "routeMiddleware" for "throttle" action:


protected $routeMiddleware = [
    .........,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];