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 :
Middleware can be created using "Artisans" CLI by executing the following command
For example, we will create First Middleware using "Artisans" CLI
Now, you can see our new Middleware at app\Http\Middleware
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.
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.
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
loginController.php at app\Http\Controllers\loginController.php has created for you, and we will register the Controller Middleware to this Controller like,
See you next Lessons..........
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 :
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
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 :- Global Middleware
- Route Middleware
- 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