Create Middleware in Laravel 5

Laravel 5 included a new feature middleware, Which not allow entering within app until user passed several conditions. In this part of tutorial we trying to create a middleware which allow users to download files. 

Let's see our middleware class.

<?php namespace App\Http\Middleware;

use Closure;
use App\User;
use Illuminate\Support\Facades\Auth;             //For accessing Auth credetials

class ifNotPermittedToDownload {

	/**
	 * Handle an incoming request.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Closure  $next
	 * @return mixed
	 */
	public function handle($request, Closure $next)
	{
        $userType = Auth::user()->user_type;
        if( $userType !== 'subscriber' ){
            return 'Not authorized for download this file';
        }
		return $next($request);
	}

}

Middleware class have a handle() method who have all logics. Inside the handle method we have a variable $userType which getting authenticated user usertype.

Suppose, There are several types of users 'userType' like free, contributor and subscriber and you want some file of your application only subscriber userType can download and other will deny the request.

  Ok, We have a condition if it's true then user can't download file otherwise he get those files with $next($request) which allow user to get next layer of the request.

Kernel.php(App\Http\kernel.php)

<?php namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel {

	/**
	 * The application's global HTTP middleware stack.
	 *
	 * @var array
	 */
	protected $middleware = [
		'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
		'Illuminate\Cookie\Middleware\EncryptCookies',
		'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
		'Illuminate\Session\Middleware\StartSession',
		'Illuminate\View\Middleware\ShareErrorsFromSession',
		'App\Http\Middleware\VerifyCsrfToken',
	];

	/**
	 * The application's route middleware.
	 *
	 * @var array
	 */
	protected $routeMiddleware = [
		'auth' => 'App\Http\Middleware\Authenticate',
		'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
		'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
        'download' => 'App\Http\Middleware\ifNotPermittedToDownload' //Added new middleware
	];

}

In this above code I just added ifNotPermittedToDownload in $routeMiddleware array.

Use middleware without Controller:

<?php
Route::get('files/download', ['middleware' => 'download', function(){
    return 'Files has been downloaded';
}]);

Add above code in routes.php file, everything will works fine.

With Controller:

<?php 
Route::get('files/download', ['middleware' => 'download', 'uses' => 'UserController@download']);

 

Open App\Http\Controllers\UserController.php file.

<?php

class UserController extends Controller {
    
    /**
	 * Create a new controller instance.
	 *
	 * @return void
	 */
    public function __construct()
    {
        // This middlware only work for download() method of this class.
        $this->middleware('download', ['only' => 'download']);
    }

    /**
     * @return string
     */
    public function download()
    {
        return 'Files has been downloaded';
    }
}

Inside __construct(), Middleware has 2 parameters first parameter is download middlware and second for download method.

Something to say? Tell us in comment section.