One place for hosting & domains

      Get Laravel Route Parameters in Middleware


      Today we’ll be talking about how to use route parameters in middleware, a task that may come up in your workflow.

      What is Middleware?

      A middleware simply wraps an application’s request. Think of it this way, when a request is made to your application, there’s code that handles the request, but if you want something to occur before or after the code that handles the request is run, you would put in a middleware.

      Laravel comes with a few inbuilt middlewares for maintenance, authentication and CSRF protection, which are all found in the app/Http/Middleware directory inside a laravel project folder.

      Laravel Route Parameters

      Laravel routes are located in the app/Http/routes.php file. A route usually has the URL path, and a handler function callback, which is usually a function written in a certain controller.

      // Inline function to handle the route
      Route::get('/', function () {
          return view('welcome');
      });
      
      // Controller function to handle the route
      Route::get('/profile', 'ProfileController@index');
      

      A parameter provided in the route is usually annotated with curly braces. For instance, to pass in a name parameter to a route, it would look like this.

      Route::get('/params/{name}', function ($name) {
          return $name
      });
      

      By convention, the Controller function accepts parameters based on the parameters provided.

      Accessing Route Parameters

      Accessing parameters in a middleware however is not that direct. First let’s create a middleware called DumpMiddleware that dumps the parameters provided in the route.

      php artisan make:middleware DumpMiddleware
      

      The file app/Http/Middlware/DumpMiddleware.php is created.

      Method 1: $request->route('parameter_name')

      We can access route parameters in two ways. One way is by using $request->route('parameter_name')., where parameter_name refers to what we called the parameter in the route. In the handle method within the DumpMiddleware class created in the app/Http/Middleware/DumpMiddleware.php file.

      public function handle($request, Closure $next)
      {   
          dd($request->route('parameter_name'));
          return $next($request);
      }
      

      To see the middleware in action, let’s add it to the route. Quickly create the route we showed above and add the middleware in the app/Http/routes.php file.

      Route::get('/params/{name}', [
          'middleware' => 'AppHttpMiddlewareDumpMiddleware',
           function () {
              return view('welcome');
      }]);
      

      We need the full namespace of the middleware, because we have not made Laravel aware of our new middleware. To do this we add it in the AppHttpKernel.php file, as part of the $routeMiddleware class property.

      protected $routeMiddleware = [
          // Middlewares commented out for brevity
          'DumpMiddleware' => AppHttpMiddlewareDumpMiddleware::class,
      ];
      

      You can then update the middleware in the route to be 'middleware' => 'DumpMiddleware',.

      Run php artisan serve on your terminal and open http://localhost:8000/params/scotch. You should see scotch dumped in the browser.

      Method 2: $request->route()->paremeters()

      The other way to access the Route parameters in the middlware involves gettting all the parameters. Imagine you had a route like this /params/{id}/{category}/{name}. All the route params are usually saved in an array, which in a middleware is accessible through $request->route()->parameters(). If we update our route to the above route,

      Route::get('/params/{id}/{category}/{name}', [
          'middleware' => DumpMiddleware',
           function () {
              return view('welcome');
      }]);
      

      And update the middleware’s handle method to,

      public function handle($request, Closure $next)
      {   
          dd($request->route()->parameters());
          return $next($request);
      }
      

      Going to http://localhost:8000/params/23/scotch/school should dump the parametes in your browser as an array, with the parameter names as the keys, and what was passed as values.

      Why Access Route Parameters in Middleware?

      A sample usage for accessing route parameters in middleware is when a given route performs different actions. Say for instance you have a route that returns user’s profiles, /{username}. To go to Scotch’s profile for instance, one would go to http://localhost:8000/scotch.

      This app, however, may have some routes that do not necessarily belong to profiles. Like faq, or support, or help. In such a scenario, it is usually recommended to have these routes defined before the route that looks for a profile.

      app/http/routes.php

      Route::get('/faq', function() {
          return view('faq');
      });
      Route::get('/help', function() {
          return view('help');
      });
      Route::get('/support', function() {
          return view('support');
      });
      
      // Route that handles profile comes last
      Route::get('/{username}', function() {
          return view('profile');
      });
      

      With middleware however, all we need to do is check if a value is in a defined array and redirect.

      app/Http/routes.php

      Route::get('/{username}',  [
           'middleware' => 'ProfileMiddleware',
           function () {
              return view('welcome');
      }]);
      

      Then in the profile middleware, we add this in the handle function.

      <?php
      
      namespace AppHttpMiddleware;
      
      use Closure;
      
      // Add Response namespace
      use IlluminateHttpResponse;
      
      class ProfileMiddleware
      {
          public function handle($request, Closure $next)
          {   
              $routes = ["faq", "support", "help"];
              $route = $request->route('username');
      
          // Redirect to custom page if it doesn't relate to a profile
              if (in_array($route, $routes)) {
                  return new Response(view($route));
              }
      
              return $next($request);
          }
      }
      

      We simply check if the parameter is in a given array, and return a view based on that. In case we have any other keywords that are not neccesarrily profiles, all we need to do is add them to this array. Cleaner, right?



      Source link

      Network Route Optimization Made Easy with Performance IP (Demo)


      Latency. It’s the mortal enemy of virtual dragon slayers, the bane of digital advertisers and the adversary of online retailers. Every end user has experienced the negative effects of latency, and even though they don’t always understand the intricacies of routing traffic through a global network, their responses to that latency can have a lasting impact on the companies whose networks aren’t functioning at peak performance.

      Consider this: More than seven in 10 online gamers will play a lagging game for less than 10 minutes before quitting. As much as 78 percent of end users will go to a competitor’s site due to poor performance. And a one second delay can cause an 11 percent drop in page views, a seven percent drop in conversions and a 16 percent drop in customer satisfaction. For online merchants, even the big boys like Amazon, each one-second delay in page load time can lead to losses of $1.6 billion annually.

      Milliseconds matter. Anyone focused on network optimization knows this. But did you know that Border Gateway Protocol (BGP) only routes traffic through the best path around 18 percent of the time? The lowest number of hops does not equate to the fastest route. And yet seeking a path with the least hops is the default.

      What if there was a better way to find the lowest latency route to reach your end users?

      Find the Fastest Network Route with Performance IP®

      With INAP, finding the lowest latency route doesn’t require you to lift a finger. Customers in our data centers are connected to our robust global network and proprietary route optimization engine. Performance IP® enhances BGP by assessing the best-performing routes in real time.

      This technology makes a daily average of nearly 500 million optimization across our global network to automatically put your outbound traffic on the best-performing route. And with the meshed infrastructure of Tier 1 ISPs and our global network, you don’t have to choose between reliability, connectivity and speed. You can download the data sheet on Performance IP®here.

      “In online games, lag kills,” said Todd Harris, COO of Hi-Rez Studios, an INAP customer. “To deliver the best experience, we have to make sure that gamers are able to play on the best network while using the most efficient route. INAP delivers all of that.”

      Skeptical about what Performance IP® can do for you? Let’s run a destination test. Below, we’ll take you through the test step by step so you can get the most out of the demo when you try it for yourself.

      Breaking Down the Performance IP® Demo

      You can access the demo from the INAP homepage or the Performance IP® page. Get started by entering your website URL or any destination IP. We’ll use ca.gov for our test purposes.

      Performance IP Homepage

      Next, choose your source location. The locations in the drop-down menu represent INAP’s data centers and network points of presence where you can take advantage of the Performance IP® service. Each market has a different blend of Tier 1 ISPs. Performance IP® measures all carrier routes out of the data center and optimizes your traffic on the fastest route to your target address.

      Here, we’re running the test out of our Atlanta flagship data center, but you can test out all of our markets with the demo. We’ll run the route optimization test to our sample website, which is located in California. Once you have all your information entered, click “Run Destination Test.”

      Destination test
      Click to view full-size image.

      As you can see from the result of our test above, the shortest distance is not the lowest latency path. Each Greek letter on the chart represents an automonous system (AS). The Performance IP® service looked at seven carriers in this scenario and was able to optimize the route so that our traffic gets to its destination 21.50 percent faster—16.017 ms faster—than the slowest carrier.

      Destination Test Summary
      Click to view full-size image.

      In the traceroute chart above, we can study the latency for the each carrier more closely. Although in this scenario the best perfroming carrier passed though three automous systems while all of the other carriers passed through only two, it was still the fastest. Note that default BGP protocol would have sent us through any of the other carriers, including the slowest route through Carrier 3.

      Once you’ve had time to adequately study the outcome of the test, click “Continue” to see carrier performance over the last month. This chart measures the percentage of carrier prefixes originating from our Atlanta POP that had the best and worst performing routes for any given day of the month. While individual carrier performance can vary radically, if you’re a Performance IP® customer this won’t be a concern for you. Since the engine measures network paths millions of times a day, Performance IP® sends outbound traffic along the lowest latency path virtually 100 percent of the time.

      The final tab of the demo allows you to study our product line-up and open a chat to get a quote. Performance IP® is available for INAP colocation customers and is included with INAP Cloud products. If you’re not interested in these infrastructure solutions, you can still purchase Performance IP® from one of our data centers and connect it to your environment.

      Run the test for yourself, or chat with us now to get a quote.

      Explore the INAP Performance IP® Demo.

      LEARN MORE

      Laura Vietmeyer


      READ MORE



      Source link

      How to Prevent Route Leaks with Inbound and Outbound Route Mapping


      As citizens of the internet, it’s our responsibility to be a good neighbor by configuring and managing an autonomous system (AS) that follows proper Border Gateway Protocol (BGP). Improper configuration and management can hold dire consequences, including route leaks.

      During the summer, a high-profile route leak event prevented access to Amazon, Facebook, Cloudflare and others over a two hour period. Let’s explore route leaks in greater depth and learn how events like this can be prevented. If you’d like to brush up on BGP and how default BGP can impact your network performance before diving in, you can get a refresher here.

      What is a Route Leak?

      Simply put, a route leak occurs when internet traffic is routed through unintended paths. More specifically, route leaks happen when an AS advertises prefixes it’s not entitled to advertise.

      When an AS advertises prefixes it should not be announcing, some or all traffic destined for the prefix will get redirected to the unwarranted AS, never reaching the intended destination. This is often due to BGP misconfigurations but can also be the result of malicious intent.

      The high-profile route leak event over the summer was caused by a small company advertising more specific prefixes introduced by a route optimization appliance. This event could have been avoided if either the small company or its upstream ISPs had followed some basic best practices in their BGP configurations to eliminate the risk of a route leak.

      Avoiding Route Leaks with Route Mapping

      A small company advertising prefixes to upstream ISPs can use route maps to effectively prevent re-announcing incorrect prefixes. Route maps can be used both on the inbound and the outbound BGP sessions.

      In the event mentioned above, an inbound route map should have been used on the BGP session with the route optimizer and set the well-known BGP community for NO EXPORT on routes received. The NO EXPORT BGP community informs the receiving router’s BGP process that it should not advertise the prefixes heard on this session to External Border Gateway Protocol (eBGP) neighbors. This would have prevented any more specific prefixes from being leaked to the upstream ISPs.

      Inbound Route Maps

      ISPs can use inbound route maps with their customers to limit their expected prefixes. The inbound route map matches only a set of prefixes the customer can announce (as informed by route registries) and allows those routes in the ISP’s route tables.

      The ISP can also limit the number of prefixes that a customer can announce before shutting down the BGP session using the maximum-prefix feature. Using maximum-prefix does not necessarily keep an AS from advertising errant routes, but it can limit the scope of a potential route leak.

      Outbound Route Maps

      Outbound route maps can also be configured by an advertising AS to limit the prefixes that are sent out via BGP. Like the inbound route map on the ISP side of the BGP session, the downstream AS can use an outbound route map to match a prefix list with prefixes a company is permitted to advertise. This prevents any additional prefixes from getting into the ISP’s route tables and out to the larger internet.

      Closing Thoughts

      Route leaks, and to some degree route hijacking, which is defined by malicious intent, are avoidable as long as AS entities and their upstream providers take the time to configure BGP properly to avoid them. Inbound and outbound route mapping are just a couple of best practices that can eliminate potential route leaks before they become major problems.

      Explore INAP’s Global Network.

      LEARN MORE

      David Heidgerken


      David Heidgerken is a Solution Engineer, aligning technical specifications with customer expectations to create IT solutions that successfully deliver better technological outcomes. READ MORE



      Source link