laravel ÉÏ°¶ºóÌøת
ÔÚ¿ª·¢ web Ó¦ÓóÌÐòʱ£¬Óû§µÇ¼ÈÏÖ¤ÊÇÒ»¸ö±Ø²»¿ÉÉٵĹ¦Ð§¡£laravel ¿ò¼ÜÌṩÁ˶àÖÖ·½·¨ÊµÏÖÓû§ÈÏÖ¤£¬²¢ÇÒ»¹ÌṩÁËÒ»Ì×ĬÈϵÄÉí·ÝÈÏ֤ϵͳ£¨¼´ laravelilluminateauth£©£¬Àû±ã¿ª·¢ÕßÔÚÓ¦ÓóÌÐòÖÐʵÏÖÓû§×¢²á¡¢µÇ¼¡¢Í˳öµÈ¹¦Ð§¡£
¹ØÓڵǼÈÏÖ¤Àֳɺó£¬ÎÒÃǾ³£Ï£ÍûÌøתµ½Ìض¨Ò³Ã棬ºÃ±ÈÓû§µÄСÎÒ˽¼Ò×ÊÁÏÒ³£¬»òÕßij¸öÌض¨¹¦Ð§Ò³¡£ÔÚ Laravel ¿ò¼ÜÖУ¬ÊµÏֵǼºóÌøתºÜÊǼòÆÓ¡£
±¾ÎĽ«ÏÈÈÝ Laravel ¿ò¼ÜÖÐÓû§µÇ¼ºóÌøתµÄ¼¸ÖÖ·½·¨¡£
Laravel ¿ò¼ÜĬÈϵĵǼÌøת
LaravelIlluminateAuth ÌṩµÄÉí·ÝÈÏ֤ϵͳĬÈÏÉèÖÃÁËÓû§µÇ¼ºóµÄÌøת¡£ÔÚ config/auth.php ÉèÖÃÎļþÖУ¬ÓÐÈçÏÂĬÈÏÉèÖãº
'redirect' => [ 'login' => '/login', 'logout' => '/logout', 'home' => '/home', 'register' => '/register', 'verify' => '/email/verify', 'reset' => '/password/reset', 'confirm' => '/password/confirm', ],
µÇ¼ºó¸´ÖÆ
ÆäÖУ¬’home’ ÌåÏֵǼºóµÄÌøתҳÃ棬ĬÒÔΪ /home ·¾¶¡£ÈôÊÇÐèÒªÐÞ¸ÄĬÈÏÌøתҳÃ棬ֻÐèÒª½«¸Ã·¾¶ÐÞ¸ÄΪ×Ô¼ºÏëÒªµÄÒ³Ãæ¼´¿É¡£
ÊÖ¶¯Ö¸¶¨Ìøת·¾¶
ÈôÊÇÐèÒªÔÚ¿ØÖÆÆ÷ÖÐÊÖ¶¯Ö¸¶¨µÇ¼ºóµÄÌøתҳÃ棬ÎÒÃÇ¿ÉÒÔʹÓà Laravel ¿ò¼ÜÌṩµÄ RedirectResponse ʵÀý£¬Í¨¹ý redirect() ÒªÁìʵÏÖ¡£
ÀýÈ磬ÔÚÓû§¿ØÖÆÆ÷ÖУ¬ÎÒÃÇ¿ÉÒÔÖØд IlluminateFoundationAuthAuthenticatesUsers trait ÖÐµÄ authenticated() ÒªÁ죺
use IlluminateSupportFacadesAuth; class UserController extends Controller { use AuthenticatesUsers; protected function authenticated(Request $request, $user) { return redirect()->route('user.show', $user->id); } }
µÇ¼ºó¸´ÖÆ
ÉÏÊö´úÂë¿ÉÒÔÔÚÓû§µÇ¼Àֳɺó£¬Ìøתµ½Ö¸¶¨µÄÓû§Ð¡ÎÒ˽¼Ò×ÊÁÏÒ³¡£
Öض¨Ïòµ½ÏÈÇ°Ò³Ãæ
ÓÐʱ¼ä£¬ÎÒÃÇÐèÒª½«Óû§µÇ¼ºóµÄÌøת·¾¶ÉèÖÃΪµÇ¼֮ǰµÄÒ³Ã棬¿ÉÒÔʹÓà Laravel ÌṩµÄ session() º¯ÊýºÍ URL::previous() ÒªÁì¡£
ÀýÈ磬ÔڵǼ¿ØÖÆÆ÷ÖУ¬ÎÒÃÇ¿ÉÒÔÕâÑùʵÏÖ£º
use IlluminateHttpRequest; use IlluminateSupportFacadesAuth; use IlluminateSupportFacadesURL; class LoginController extends Controller { public function login(Request $request) { $credentials = $request->only('email', 'password'); if (Auth::attempt($credentials)) { return redirect()->intended(URL::previous()); } return back()->withErrors(['email' => 'µÇ¼ʧ°Ü']); } }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÊö´úÂëÖУ¬ÎÒÃÇʹÓÃÁË redirect()->intended() ÒªÁ죬¸ÃÒªÌå»á½«Óû§Öض¨Ïòµ½µÇ¼֮ǰ»á¼ûµÄÒ³Ãæ¡£ÈôÊÇÓû§Ö®Ç°Ã»Óлá¼û¹ýÆäËûÒ³Ã棬Ôò»áÖض¨ÏòÖÁĬÈϵĵǼÌøת·¾¶¡£
ʹÓÃÖÐÐļþÌøתµ½Ö¸¶¨Ò³Ãæ
Laravel ¿ò¼ÜÖÐÐļþÌṩÁ˱ã½ÝµÄÉí·ÝÈÏÖ¤ºÍÊÚȨ¹¦Ð§¡£ÎÒÃÇ¿ÉÒÔÔÚijÆäÖÐÐļþÖÐÖ¸¶¨µÇ¼ºóµÄÌøת·¾¶¡£
ÀýÈ磬ÎÒÃÇ¿ÉÒÔÔÚ auth ÖÐÐļþÖÐÉèÖõǼºóµÄÌøת·¾¶£º
namespace AppHttpMiddleware; use IlluminateAuthMiddlewareAuthenticate as Middleware; class Authenticate extends Middleware { protected function redirectTo($request) { if (! $request->expectsJson()) { return route('login'); // ÉèÖÃĬÈϵÄÌøת·¾¶ } } }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÊö´úÂëÖУ¬ÎÒÃÇʹÓà redirectTo() ÒªÁìÀ´´¦Öóͷ£µÇ¼ʧ°ÜµÄÇëÇó¡£ÈôÊÇÇëÇóʱÆÚÍû·µ»Ø json ÃûÌÃÊý¾Ý£¬ÔòÖ±½Ó·µ»Ø 401 ¹ýʧ£»²»È»£¬½«Óû§Öض¨Ïòµ½µÇ¼ҳÃæ¡£
ÈôÊÇÐèÒªÖ¸¶¨ÆäËûµÄÌøת·¾¶£¬Ö»ÐèÒªÐÞ¸Ä return Óï¾äÖеÄ·ÓÉÓÖÃû¼´¿É¡£
×ܽá
ÒÔÉϾÍÊÇÔÚ Laravel ¿ò¼ÜÖÐʵÏÖÓû§µÇ¼ºóÌøתµÄ¼¸ÖÖ·½·¨¡£ÏêϸѡÔñÄÄÖÖ·½·¨£¬È¡¾öÓÚ¿ª·¢ÕßµÄÏÖʵÐèÇóºÍ¿ª·¢³¡¾°¡£ÎÞÂÛÊÇÄÄÖÖ·½·¨£¬¶¼¿ÉÒÔÀû±ã¿ì½ÝµØ×ÊÖúÎÒÃÇʵÏÖÓû§ÈÏÖ¤¹¦Ð§ºÍµÇ¼ºóµÄÌøת¡£
ÒÔÉϾÍÊÇlaravel ÉÏ°¶ºóÌøתµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡