CodeIgniter Laravel PHP Example HTML Javascript jQuery MORE Videos New

How to create custom Middleware in laravel


    Steps:
  1. run command in terminal
    php artisan make:middleware PermissionCheck go to app/Http/Middleware and open the PermissionCheck.php file there is handle(Request $request, Closure $next) method. we have to write the code in this function.
  2. open Kernel.php which is inside under app/Http folder
    add 'permission_check' => \App\Http\Middleware\PermissionCheck::class, inside routeMiddleware list
  3. use $this->middleware('permission_check'); statement to load middleware.

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class PermissionCheck
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $route = $request->route()->uri();
        $methodArray = $request->route()->methods();
        $method = $methodArray[0];
        /* dd($method); */
        $allow_method =  ["GET","POST","PUT","DELETE"];
        if(in_array($method,$allow_method)){
            $request->merge(array("addedInMiddleware" => true));
            /* /** */
            /*  * This variable is available globally on all your views, and sub-views */
            /*  */
            view()->share('my_global_variable', "I am global for view");
            return $next($request);
        }
        else{
            return new Response(view('404')); 
        }
        /* return $next($request); */
    }
}