title: API - validating request in Laravel
body: <p>I am creating a simple API for uploading files from mobile app. </p>
  
  <p>In my <code>routes/api.php</code> file I have a route defined:</p>
  
  <pre><code>Route::post("/file", 'UploadController@upload');
  </code></pre>
  
  <p>then in my controller I validate the request:</p>
  
  <pre><code>public function upload(Request $request){
  
      $this-&gt;validate($request, [
              'name' =&gt; 'required',
              'file' =&gt; 'file',
              'type' =&gt; 'required|in:sign,photo',
          ]);
  
       // do something here....
  
  }
  </code></pre>
  
  <p>When the request is correct (it passes the validation) everything works fine and Laravel returns JSON response. </p>
  
  <p>But if the request does not pass the validation, i.e. the <code>name</code> field is missing, Laravel returns 302 page and tries to redirect me to login page. </p>
  
  <p>How can I return proper 40X/50X error with JSON message when validation fails, instead of 302 redirect page? </p>
  
  <p>I'm using Laravel 5.3 and <a href="https://insomnia.rest" rel="nofollow noreferrer">Insomnia</a> for testing the API calls. </p>