Same Issue
I had this issue - and did not want every controller action to worry about what this helper could deal with, so I figured that "Needs to be returned to the browser" could be accomplished by an echo
and exit;
My Solution
// Redirect to the login?
if (empty($admin) || empty($token)) {
// I have to echo the redirect in order to return the response from here.
echo redirect('/admin/login');
exit;
}
More Explanation
Redirect - set headers only, before output.
When you redirect in PHP, you are only setting headers - that's what the redirect()
function will do. This function derives to a Redirect Facade method to(), which returns a laravel RedirectResponse
. When "echoing" it should only give back a response with headers and no body.
This means you cannot start outputting before the redirect. Remove any var_dumps, included template/view files, or other echos! Even a blank string or line space in a template file can ruin this.
Remember, you are server-side!
You would not be able to (due to errors - see headers already sent), or want to, redirect in the middle of a template file, because PHP is the language that is processed on the server side - so just once... if you need to be redirecting within a rendered view (probably based on some condition), use javascript!
More about "echo"
Because we are doing an echo redirect()
, you may be scared of what the echo means. It is just sending back the full response (with only headers if done right!)
Sometimes I think that it is harder for people to realize that the only way PHP can ever send back a response (headers and the body) is through an echo (or similar outputting functions eg. printf, var_dump, etc), but most frameworks do not make you aware of this, so your only experience with echo is inside of templates.
Ps. Some frameworks utilize output_buffering to store the "echo" results in a buffer for last minute processing before sending everything.
Test it in your network tab of your browser
If you are doing it right, in the network tab of the browser, you will see a status code of 302 and the response section will say "Failed to load a response..." because it was redirecting.
If you are seeing the URL or anything else in the response tab, eg. the url , it is likely because you are sending out content via a var_dump, including a template file, or another echo that is creating a response body. Try using your browser network tab and preserve the log to see what is happening.
Even sending an empty string or line break counts as a response body (hence blank page). Typically you should get warnings about trying to set headers after some of the response body has already been sent in PHP. Basically, you should not be including a template or echoing anything out before a redirect. Your logic should process the redirect first thing!
The exit
is there to make sure it does not go on to include your view or echo more things out!