神刀安全网

Creating your first middleware in Laravel 5

Middlewares can help us execute different application logic in numerous routes so that we do not repeat ourselves.

They are good for filtering HTTP requests. For example, you can create a middleware which redirects user that are not authorized to view a page to another page or you can create a middleware which disallows guests from accessing pages (in fact, Laravel has such a middleware built-in). You can create a middleware which sets some HTTP headers. For example, you can enable CORS so that AJAX requests can be made from everywhere to some particular routes.

Creating your first middleware in Laravel 5

To show you how to build a middleware we are going to build a middleware which gets some Geolocation information from the user’s IP address and makes it accessible to the controller. Then, any controller that uses that middleware in its route settings will be able to use the Geolocation information about the user. The Geolocation would be saved in the user’s session so that we do not make a request to the API every time a user requests a new page.

Creating a new middleware with Artisan

To make a new middleware we start our Command Line/Terminal, go to the directory where our Laravel project is and type: php artisan make:middleware getClientInformation . getClientInformation could be anything and it represents the name of our middleware (the appropriate file would be named getClientInformation in our case).

After you execute the command, you will see a file with the name getClientInformation.php in the directory path: app/http/middleware . We would have to insert our middleware functionality there.

Registering the middleware

Before that, we navigate to app/Http/Kernel.php and introduce our middleware to Laravel. Inside the  $routeMiddleware array we add the following index:

'getClientInfo' => /App/Http/Middleware/getClientInformation::class, 

This would set a middleware available for use in our routes located in the routes.php file with the alias of getClientInfo. The value is just the namespace of our middleware (which is automatically set up by the Terminal command that we typed in the beginning).

In the created file, you can see the namespace:

namespace App/Http/Middleware;   Theclass is automaticallycreated:   class getClientInformation   { 

Therefore, in Kernel.php’s $routeMiddleware property our middleware’s namespace would look like the following:

/App/Http/Middleware/getClientInformation::class, 

Using the middleware

Now, to use the our middleware, we can go to our routes.php file and provide an array of options in which we declare a middleware key with value corresponding to the key we have put in the Kernel.php file (the $routeMiddleware array). Our middleware would now be used for that route. We would not create a controller here but you can (we will just provide an anonymous function). In our controller, we will get the clientInfo attribute that is set on the request by our middleware and display the properties in the user’s browser.

Route::get("/", ['middleware' => "getClientInfo", function() {   $clientInfo = Request()->attributes->get("clientInfo");   echo "It seems like you are based in " . $clientInfo->city . ", " . $clientInfo->country . ".<br>";   echo "Is your region (" . $clientInfo->regionName . ") nice to live in?";   }]); 

Creating the actual Laravel 5 middleware

What is inside the middleware file ( app/Http/Middleware/getClientInformation.php ) is mostly boilerplate created by our initial Artisan command. We just type inside the handle method. There, we check if there is a session property called clientInfo – if there is none we make a request to the API, provide it the client IP address, set the session property to the API’s response and bind the API’s response to the request. If there is already a session property with the Geolocation data – we just bind it to the request attributes (we can retrieve it from the controllers which use the middleware)

<?php   namespace App/Http/Middleware;   use Closure;   use Illuminate/Support/Facades/Request;   use Illuminate/Support/Facades/Session;     class getClientInformation {       /**        * Handle an incoming request.        *        * @param  /Illuminate/Http/Request  $request        * @param  /Closure  $next        * @return mixed        */       public function handle($request, Closure $next)       {           if (!Session::get("clientInfo")) {               $ip =  Request::ip() && Request::ip() !== "127.0.0.1" ? Request::ip() : "126.15.33.125";               $data = json_decode(file_get_contents("http://ip-api.com/json/" . $ip));               Session::set("clientInfo", $data);               $request->attributes->add(["clientInfo" => $data]);           }           $request->attributes->add(["clientInfo" => Session::get("clientInfo")]);           return $next($request);       }   } 

Conclusion

Now, our index route will return a response similar to the one in the picture below:

Creating your first middleware in Laravel 5

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Creating your first middleware in Laravel 5

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址