[Tutorial] Vernacular Laravel Middleware

Keywords: PHP Laravel Session

The article is transferred from: https://learnku.com/laravel/t...

What is Laravel middleware?

In short, the role of Middleware in laravel is to filter HTTP requests and perform different logical operations according to different requests.

We can achieve the following functions through middleware:

  • Specify certain routes
  • Setting up HTTP response headers
  • Record request
  • Parameters for filtering requests
  • Determine whether site maintenance mode is enabled
  • Do some necessary actions before and after the response

Custom Middleware

By executing the following simple commands from the command line, you can easily create a new Middleware

php artisan make:middleware <MiddlewareName>
//Middleware Name is the name of the middleware you want to create

By executing the above command, Laravel automatically creates a middleware containing only handle methods in the app/Http/Middleware directory.

<?php
namespace App\Http\Middleware;
use Closure;
class RedirectIfSuperAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request);
    }
}

When the middleware is called, the handle method executes. Here needs to note that the handle method defaults to two parameters, $request and $next. The $request is used to accept the application's request group request, and $next passes the request to the application. These two parameters are essential to handle!E and post-middleware.

Pre-middleware, as its name implies, handles some logic before forwarding requests to applications. On the other hand, after middleware, it runs after the application processes the request and generates the response.

Pre-middleware:

<?php
namespace App\Http\Middleware;
use Closure;
class RedirectIfSuperAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        //Here's your logic.
        return $next($request);
    }
}

Post-middleware:

<?php
namespace App\Http\Middleware;
use Closure;
class RedirectIfSuperAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        //Your logic is here, for example, redirecting to`/`

        return $response;
    }
}

Categories of Middleware

  • Global Middleware
  • Routing Middleware

The global middleware runs for each request that hits the application. Laravel comes with most of these middleware, such as ValidatePostSize, TrimStrings, CheckForMaintenance Mode, and so on.

Routing middleware runs only on the routes they connect to
For example, redirectIf Authenticated.

Registration Middleware

Any middleware created must be registered, because this is the only way Laravel knows it exists. To register the middleware, simply open a file named kernel.php, which is located in the Http folder, as follows:

This file contains list of all registered middlewares that come with Laravel by default. it contains three major arrays which
This file contains a list of all registered middleware provided by default Laravel. It contains three main middleware groups: $middleware, $middleware Groups, and $routeMiddleware

<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
    /**
     * Global HTTP middleware for applications.
     *
     * These middleware runs during each request of the application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \App\Http\Middleware\TrustProxies::class,
    ];
    /**
     * Application routing middleware group.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];
    /**
     * Application routing middleware.
     *
     * These middleware can be assigned to groups or used separately.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        //the just created middlware
        'superadmin' => \App\Http\Middleware\RedirectIfSuperAdmin::class, 
    ];
}

The $middleware array contains global middleware, which runs every HTTP request of the application, so if you want to run a middleware for each request, you should register it here. $middleware Groups enables middleware to be registered in groups, making it easier to attach a large number of middleware to routing by using group names. The $routeMiddleware array contains each registered routing middleware.

Distribution Middleware

There are two main ways to apply registered middleware to routing.

  • Constructing Method of Controller
  • Routing

Distribution of Middleware by Constructive Method

There is a great deal of flexibility in allocating the middleware by constructing methods. It provides two important methods, except($parameters) and only($parameters), which allow or prevent middleware from being applied to auxiliary methods in controllers. Without these two methods, the middleware will use each method with the controller.

<?php
use Illuminate\Http\Request;

class ForumController extends Controller
{

    public function __construct(){
      /**in this case the middleware named auth is applied
       to every single function within this controller
       */
        $this->middleware('auth');
    }

    public function viewForum(){

      return view('index');
    }

    public function edit($id){

    }

    public function delete($id){

    }

}

Using the except and only methods, we can choose to apply the middleware to the specified method.

<?php
use Illuminate\Http\Request;

class ForumController extends Controller
{

    public function __construct(){
      /**the authentication middleware here applies to all functions but
       viewForums() and viewForumDetails() and the opposite of this happens
       when you use only()
       */
        $this->middleware('auth')->except(['viewForums', 'viewForumDetails']);
    }

    public function viewForums(){

      return view('index');
    }

    public function edit($id){

    }

    public function delete($id){

    }

    public function viewForumDetails(){

    }
}

Distributing middleware through routing

If the registered middleware can be attached directly to the routing, as follows:

<?php
//Method 1
Route::get('admin/profile', function () {
  //action
})->middleware('auth');

/**Method 2
 Or use fully qualified class names like this:
*/
use App\Http\Middleware\CheckAge;

Route::get('admin/profile', function () {
    // action
})->middleware(CheckAge::class);

//Method 3
Route::group(['middleware' => ['web']], function () {
    //action
});

N:B Middleware Group can be assigned to routing as a single Middleware

Middleware parameters

Other parameters can be passed to the middleware. A typical example is to assign each user ID to a role, and the middleware checks the user's role to determine whether it has access to the requested URI. The parameters can be passed to the middleware as follows:

<?php
//Method 1
Route::get('admin/profile', function () {
  //action
})->middleware('auth:<role>'); //<role> This should be replaced by any parameters that the user wants to pass.

//Method 2 (Through a controller)
use Illuminate\Http\Request;

class ForumController extends Controller
{

    public function __construct(){
        $this->middleware('auth:<role>');
    }
  }

By separating each parameter by commas, multiple parameters can be passed to the middleware.

<?php
Route::get('admin/profile', function () {
  //action
})->middleware('auth:<role>,<age>,<country>'); //<role>, <age>, <country> here should be replaced by any parameters that the user wants to pass.

These parameters are passed to the handle function of the middleware after the $next variable

<?php
class RedirectIfSuperAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next, $role, $age, $country)
    {   
        //Middleware logic using parsing parameters
        return $next($request);
    }
}

summary

To create middleware, follow these steps

  • Use the artisan command to create the middleware php artisan make:middleware middleware name.
  • Register Middleware in kernel.php in app_Http folder
  • Writing logic in the created Middleware
  • Assigning middleware to routing or controller

Conclusion

Laravel middleware can more easily protect our routing, filter input and do a lot of other work without writing so much logic. View the official Laravel document Here To learn more about middleware, the most important thing is to practice.

The article is transferred from: https://learnku.com/laravel/t...

More articles: https://learnku.com/laravel/c...

Posted by NoPHPPhD on Thu, 09 May 2019 11:30:39 -0700