Laravel 5 Tutorial : How to use Middleware in Laravel

Laravel 5 Tutorial for beginners : how to use middleware and understanding middleware parameter in Laravel 5.3

Laravel 5 Tutorial - What is Middleware? In the context of Laravel Artisans Framework, the Middleware is a special Class that acts as a "mediator" between the incoming request with the other Controller. Middleware in Laravel will intercept the incoming request then will be processed before given to the Controller that the intended or directed to another Controller. By using this feature, we can create reusable components to perform these works.

For example, Laravel includes a middleware that verifies whether user of the application is authenticated or not. If the user authenticated, She will be redirected to home pages, if not She will redirected to the login page.

Please Read :
  1. How to Install Laravel 5 on Localhost
  2. What's New in Laravel 5.3?

How To Define Middleware in Laravel?

 By default, in Laravel 5.3 has been providing for three Middleware with the name app\Http\Middleware\EncryptCookies.php, app\Http\Middleware\RedirectIfAuthenticated.php, and app\Http\Middleware\VerifyCsrfToken.php located in app\Http\Middleware directory.

Middleware can be created using "Artisans" CLI by executing the following command

php artisan make:middleware 

For example, we will create First Middleware using "Artisans" CLI

How to use Middleware in Laravel

c:\server\htdocs\laravel>php artisan make:middleware LoginMiddleware
Middleware created successfully.

Now, you can see our new Middleware at app\Http\Middleware

<?php

namespace AppHttpMiddleware;

use Closure;

class LoginMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request);
    }
}

As seen in the above Middleware code have a method that is called handle(). The method has two parameters, namely $request that Illuminate\Http\Request and $next Closure. This method will be called automatically by the Laravel when we register this middleware.

This is an example how to define the handles() method that used to filter every request that the intended address can be accessed only by the user with the admin role.

<?php

namespace AppHttpMiddleware;

use Closure;

class LoginMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
      $user = Auth::user();
        if($user->role === User::ROLE_ADMIN) {
          return $next($request);
        }
        return redirect('index');
    }
}

The loginMiddleware above is a simple code that will checked the role of the user who is currently logged on at the time. If the user that is currently logged in has the role of admin, then we will forward the incoming request and give it to the other Controller (by calling the $next method($request)). If not we will redirect that user to the index page.

Register Middleware

In Laravel Artisan Php Framework, We need to register each and every middleware before using it. There are two types of Middleware in Laravel :
  1. Global Middleware
  2. Route Middleware
  3. Controller Middleware

Global Middlware

We can add global middleware at app\Http\Kernel.php That middleware will always be invoked every incoming request.

    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \App\Http\Middleware\MyGlobalMiddleware::class, // our ne Global Middelware is here
    ];

Route Middleware

We can add Route middleware at app\Http\Kernel.php

    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,
        'myMiddlware' => \App\Http\Middleware\MyGlobalMiddleware::class, //our new Middelware
    ];

Now, after we registered te middleware using Route Middleware, write the Routes Option to the routes.php file in app\Http\routes.php on laravel 5.2 and in routes\web.php on Laravel 5.3

Route::get('admin', [
    'uses' => 'AdminController@index',
    'middleware' => 'myMiddleware'
]);

Controller Middleware

We can create a new Controller using "Artisan" CLI by Execute this command,

c:\server\htdocs\laravel>php artisan make:controller loginController
Controller created successfully.

loginController.php at app\Http\Controllers\loginController.php has created for you, and we will register the Controller Middleware to this Controller like,

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

use AppHttpRequests;

class loginController extends Controller
{
  function index(){
    $this->middleware('myMiddleware');
    $this->middleware('logMiddleware', ['only' => ['foo', 'bar']]); //selected method
    $this->middleware('subscribeMiddleware', ['except' => ['baz']]) ; //exclude method
  }
}

See you next Lessons..........

COMMENTS

Next Recomended


Feel free to code it up and send us a pull request.

Hi everyone, let's me know how much this lesson can help your work. Please Subscribe and Follow Our Social Media 'kodeajaib[dot]com' to get Latest tutorials and will be send to your email everyday for free!, Just hit a comment if you have confused. Nice to meet you and Happy coding :) all ^^



Follow by E-Mail


Name

ADO.NET,3,Ajax,6,Android,9,AngularJS,4,ASP.NET,4,Blogger Tutorials,7,Bootstrap,7,C++,1,Codeigniter,2,Cplusplus,6,Crystal Report,6,CSharp,25,Ebook Java,2,FlyExam,1,FSharp,3,Game Development,2,Java,35,JDBC,2,Laravel,84,Lumen,2,MariaDB,2,Ms Access,3,MySQL,31,ODBC,6,OleDB,1,PHP,14,PHP Framework,5,PHP MYSQLI,9,PHP OOP,5,Python,8,Python 3,4,SQL Server,4,SQLite,4,Uncategorized,5,Vb 6,2,Vb.Net,89,Video,48,Vue Js,4,WPF,2,Yii,3,
ltr
item
KODE AJAIB: Laravel 5 Tutorial : How to use Middleware in Laravel
Laravel 5 Tutorial : How to use Middleware in Laravel
Laravel 5 Tutorial for beginners : how to use middleware and understanding middleware parameter in Laravel 5.3
https://3.bp.blogspot.com/-pLhpD4gkE28/V8GwevzI5QI/AAAAAAAACVo/0RuYe0OWpQ0j64hisMPQ5sSoCgPA-XlRACLcB/s320/laravel-53-middleware-laravel-1.png
https://3.bp.blogspot.com/-pLhpD4gkE28/V8GwevzI5QI/AAAAAAAACVo/0RuYe0OWpQ0j64hisMPQ5sSoCgPA-XlRACLcB/s72-c/laravel-53-middleware-laravel-1.png
KODE AJAIB
https://www.kodeajaib.com/2016/08/how-to-use-middleware-laravel-5.html
https://www.kodeajaib.com/
https://www.kodeajaib.com/
https://www.kodeajaib.com/2016/08/how-to-use-middleware-laravel-5.html
true
3214704946184383982
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS CONTENT IS PREMIUM Please share to unlock Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy