Laravel 5 Redirect from another method

2019-06-25 10:05发布

I want to create a redirect method that could be called from other methods. Unfortunately, I can't do it as I want (see source below).

I propose a solution, but I want to redirect just calling the method, not doing more stuff.

My solution:

class FooController extends Controller
{

    public function foo(Request $request)
    {
        if ($result = $this->__check($request)) {
            return $result;
        }
        return view('foo');
    }

    private function __ckeck(Request $request)
    {
        if (doSomething) {
            return redirect('/');
        }
        return false;
    }
}

What I want:

class FooController extends Controller
{

    public function foo(Request $request)
    {
        $this->__check($request);

        return view('foo');
    }

    private function __ckeck(Request $request)
    {
        if (doSomething) {
            // redirect source <--- what I want
        }
        return false;
    }
}

2条回答
Emotional °昔
2楼-- · 2019-06-25 10:29

You should handle redirection there or return the response.

Best would be to use a customized request if you want things separate.

So after you create a new request you can simply to the checks you wish in the authorize method.

/**
 * Determine if the user is authorized to make this request.
 *
 * @return bool
 */
public function authorize()
{
    if ($this->session('foo')) {
        return true;
    }

    return false;
}
查看更多
来,给爷笑一个
3楼-- · 2019-06-25 10:37

Maybe this is what you are searching

public function foo(Request $request)
{
    return $this->check($request);
}

private function check(Request $request)
{
    if (doSomething) 
    {
       return Redirect::to('/dash'); // redirect
    }
    return Redirect::to('/');   
}
查看更多
登录 后发表回答