2

The redirect() helper function in the helper file does not work in Laravel. Here is my code helpers.php

if (! function_exists('license_check')) {
    function license_check(){
     //This does not work, returns a blank page
     return redirect()->route('loginlicense');
     //This does not work, returns a blank page
        return \Redirect::route('loginlicense');
        //This work but it prints on the browser before redirecting
        echo \Redirect::route('loginlicense');
        echo redirect()->route('loginlicense');

        //This work but it prints on the browser before redirecting
        die(\Redirect::route('loginlicense'));
        die(redirect()->route('loginlicense'));

        //The below works. But I would like to pass laravel flash sessions with `Laravel's with('status', 'My mesage')`

        $url = route('loginlicense');
     header("Location: ".$url);
        exit();
    }
}

license_check();

Why am I getting a blank page instead of being redirected to the url specified while using Redirect:: or redirect().

muya.dev
  • 966
  • 1
  • 13
  • 34
  • The response of `redirect()` and/or `Redirect::` need to be returned to the browser, and then you can `die()` the script – Quezler May 23 '18 at 10:05
  • 2
    You should handle redirections in the controller. In this function you might want to return a boolean value, or maybe throw exceptions. Then in the controller you check the function's return value (/ catch exceptions) and act accordingly. – HTMHell May 23 '18 at 10:17

3 Answers3

1

It's because invoking redirect() by calling it inside a function does not work. Just like what Quezler said, it needs to be returned to the browser.

0

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!

amurrell
  • 2,383
  • 22
  • 26
  • Thanks @amurell, is there a way to get rid of the echoed message, I mean is there any way to bypass the "echo"? – Naser Nikzad Dec 31 '22 at 10:52
  • @NaserNikzad hmm .... what are you trying to accomplish? Can you explain why the echo is a problem for you, or what your goal is - maybe what you are trying to redirect to? – amurrell Jan 03 '23 at 16:19
  • Thanks, the problem with the echo is that it displays the URL info on a blank page before doing the redirect, and this seems unfriendly to the users, or it may cause them to think it is a bug or something. – Naser Nikzad Jan 04 '23 at 06:34
  • 1
    @NaserNikzad I updated my answer with more detailed explanation that may help you out better than the limited characters I get in these comments. Look at the last section especially, about looking in your network tab to observe the response - make sure there is NO response body. If there is, you need to remove things that are outputting before or after the redirect! – amurrell Jan 05 '23 at 19:03
0

You can handle redirect in the controller. Helper function return a boolean value, or maybe throw exceptions.

helper.php

if (! function_exists('license_check')) {
    function license_check($id) {
        if($id == 2){
            return true;
        } else {
            return false;
        }
    }
}

HomeController.php

use Session;

$check_lic = license_check(2);

if($check_lic) {
    session()->flash('success', 'Your message!');
    return redirect()->route('loginlicense');
} else {
    session()->flash('error', 'you have not purchase licence!');
    return redirect()->back();
}
Fefar Ravi
  • 794
  • 7
  • 18