首页 > 解决方案 > 帮助文件中的重定向在 Laravel 中不起作用

问题描述

帮助文件中的 redirect() 帮助函数在 Laravel 中不起作用。这是我的代码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();

为什么我得到一个空白页面,而不是在使用Redirect::or时被重定向到指定的 url redirect()

标签: phplaravelredirectlaravel-5

解决方案


您可以在控制器中处理重定向。辅助函数返回一个布尔值,或者可能抛出异常。

助手.php

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

家庭控制器.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();
}

推荐阅读