Skip to content

Instantly share code, notes, and snippets.

@molayli
Created October 11, 2016 13:36
Show Gist options
  • Save molayli/2cde1317bb81fd2734fdd1a6f63ce46c to your computer and use it in GitHub Desktop.
Save molayli/2cde1317bb81fd2734fdd1a6f63ce46c to your computer and use it in GitHub Desktop.
Laravel redirect without return statment
<?php
//.....
if(!function_exists('freeRedirect')){
function freeRedirect($to = '/'){
throw new \Illuminate\Http\Exception\HttpResponseException(redirect($to));
}
}
//.............
//usage
class AbcController extends Controller{
public function aMethod(){
freeRedirect('/to/another/route');
}
}
@nshontz
Copy link

nshontz commented Jun 27, 2018

Thanks for this. using this method you can also attach flash data i.e.
throw new HttpResponseException(redirect('/to/another/route/')->with('status', 'An error occurred.'));

Also HttpResponseException moved and now lives at Illuminate\Http\Exceptions\HttpResponseException

@sergx
Copy link

sergx commented Feb 26, 2020

Thank you!

@rmdwirizki
Copy link

rmdwirizki commented Sep 5, 2020

Very helpful! Not only redirect, you can return any kind of response.
I used this to return view as well.

if(!function_exists('abortToView')){  
  function abortToView($path){   
      throw new \Illuminate\Http\Exception\HttpResponseException(response(view($path)));
  } 
}

@rdpascua
Copy link

rdpascua commented Oct 31, 2020

For laravel 8 users just change the namespace to Exceptions

if(!function_exists('abortToView')){  
  function abortToView($path){   
      throw new \Illuminate\Http\Exceptions\HttpResponseException(response(view($path)));
  } 
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment