Redirect to intended URL Lumen

隐身守侯 提交于 2019-12-13 18:21:23

问题


I'm building a little Lumen application with a simple API & Authentication.

I want to redirect the user to the intended URL and if he visits /auth/login by himself I want him to redirect to /foo.

In the Laravel Docs there is this function: return redirect()->intended('/foo');

When I use this in my route I get an error in the server log which says this:

[30-Apr-2015 08:39:47 UTC] PHP Fatal error:  Call to undefined method Laravel\Lumen\Http\Redirector::intended() in ~/Sites/lumen-test/app/Http/routes.php on line 16

I think this is because Lumen is a smaller version of Laravel and maybe this function isn't implemented (yet).


回答1:


I solved this problem by adjusting my Middleware a little bit as well as storing the Request::path() in the session.

This is how my Middleware looks:

class AuthMiddleware {

    public function handle($request, Closure $next) {
        if(Auth::check()){
            return $next($request);
        } else {
            session(['path' => Request::path()]);
            return redirect('/auth/login');
        }
    }
}

And in my routes.php I have this route (which I will outsource to a controller asap):

$app->post('/auth/login', function(Request $request) {
    if (Auth::attempt($request->only('username', 'password'))){
        if($path = session('path')){
            return redirect($path);
        } else {
            return redirect('/messages');
        }
    } else {
        return redirect()->back()->with("error", "Login failed!");
    }
});

Thanks to IDIR FETT for suggesting the Request::path() method.
Hopefully this will help a few people that are new to Lumen, which is a great framework by the way. :)




回答2:


Indeed looking at the source code of Lumen it is not implemented: https://github.com/laravel/lumen-framework/blob/5.0/src/Http/Redirector.php

Your options are:

  1. Check Laravel's (Symfony's?) implementation and put it into your own code
  2. Write completely your own implementation – one super simple way of doing it would be store the request URL in a session, redirect to the login page and when the user successfully logs in retrieve the URL from the session and redirect him



回答3:


i think you have to specify a route name in the intended method, not a URI:

return redirect()->intended('foo');

assuming you have already named the route, i think this still works as well:

return Redirect::intended('/foo');

UPDATE: try this: retrieve the requested URI :

$uri = Request::path(); // Implemented in Lumen

then redirect to the requested URI :

return redirect($uri);

this could work !!



来源:https://stackoverflow.com/questions/29963383/redirect-to-intended-url-lumen

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