Laravel 5 Redirect from another method

China☆狼群 提交于 2019-12-23 12:59:46

问题


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;
    }
}

回答1:


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;
}



回答2:


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('/');   
}


来源:https://stackoverflow.com/questions/34793770/laravel-5-redirect-from-another-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!