title: How to prevent Laravel Routes from being accessed directly (i.e. non-ajax requests)
body: <p>In my project, I am using Laravel purely as a backend api and all frontend is handled by Angular javascript. At the moment, the Laravel routes can be accessed directly and it will cough out all the data in Json that shows in the browser. I want to put a restriction on it so Laravel only responds to Ajax requests and nothing else.</p>
  
  <p>I read this post <a href="https://stackoverflow.com/questions/16591787/angular-and-laravel">here</a> which has a solution for Laravel 4 that is by adding a restriction in <code>filter.php</code>. But as of Laravel 5.1, filters are no longer used and I believe Middleware can be used to do the same. However, I am not sure how to go ahead changing the Laravel 4 solution in that SO answer from filter to Middleware.</p>
  
  <p><strong>Can someone share your ideas on how to prevent Laravel 5.1 routes from being accessed directly please?</strong></p>
  
  <p>Laravel 4 solution using <code>filter.php</code>:
  In <code>filter.php</code> declare this filter:</p>
  
  <pre><code>Route::filter('isAJAX', function()
  {
      if (!Request::AJAX()) return Redirect::to('/')-&gt;with(array('route' =&gt; Request::path()));
  });
  </code></pre>
  
  <p>Then put all your routes that you only want accessible via AJAX into a group. In your routes.php:</p>
  
  <pre><code>Route::group(array('before' =&gt; 'isAJAX'), function()
  {
      Route::get('contacts/{name}', ContactController@index); // Or however you declared your route
  
      ... // More routes
  });
  </code></pre>