ÔõÑùÔÚLaravel 5.4ÖÐʵÏÖÖÐÑë¼þÌøת
ÔÚlaravel 5.4֮ǰ£¬ÎÒÃÇ¿ÉÒÔʹÓÃÖÐÑë¼þÀ´ÊµÏÖÌøת¹¦Ð§¡£¿ÉÊÇ£¬laravel 5.4ÖÐÑë¼þµÄʵÏÖ·½·¨ÓÐËù²î±ð¡£ÔÚ±¾ÎÄÖУ¬ÎÒÃǽ«ÌÖÂÛÔõÑùÔÚlaravel 5.4ÖÐʵÏÖÖÐÑë¼þÌøת¡£
Ò»¡¢ÔÚLaravel 5.4ÖÐʵÏÖÖÐÑë¼þÌøת
ÔÚLaravel 5.4ÖУ¬ÎÒÃÇ¿ÉÒÔʹÓÃredirect()º¯ÊýºÍwith()º¯ÊýÀ´ÊµÏÖÖÐÑë¼þÌøת¡£ÏÂÃæÎÒÃÇÀ´¿´Ò»¸öÀý×Ó£º
½¨ÉèÒ»¸öÈÕÖ¾ÖÐÑë¼þ
ÔÚapp/Http/MiddlewareĿ¼Ï£¬½¨ÉèÒ»¸öLogMiddleware.phpÎļþ£¬ÄÚÈÝÈçÏ£º
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\Log; class LogMiddleware { public function handle($request, Closure $next) { Log::info('LogMiddleware'); return $next($request); } }
µÇ¼ºó¸´ÖÆ
ÉÏÃæµÄ´úÂ뽨ÉèÁËÒ»¸öÃûΪLogMiddlewareµÄÖÐÑë¼þ£¬ÔÚhandleº¯ÊýÖмͼÁËÒ»ÌõÈÕÖ¾¡£
½¨ÉèÒ»¸öÊÚȨÖÐÑë¼þ
ÔÚapp/Http/MiddlewareĿ¼Ï£¬½¨ÉèÒ»¸öAuthMiddleware.phpÎļþ£¬ÄÚÈÝÈçÏ£º
<?php namespace App\Http\Middleware; use Closure; class AuthMiddleware { public function handle($request, Closure $next) { if (!auth()->check()) { return redirect('/login')->with('error', 'ÇëÏȵǼ£¡'); } return $next($request); } }
µÇ¼ºó¸´ÖÆ
ÉÏÃæµÄ´úÂ뽨ÉèÁËÒ»¸öÃûΪAuthMiddlewareµÄÖÐÑë¼þ£¬ÔÚhandleº¯ÊýÖÐÅжÏÓû§ÊÇ·ñÒѵǼ£¬ÈôÊÇδµÇ¼£¬ÔòÌøתµ½µÇ¼ҳÃ棬²¢½«¹ýʧÐÅÏ¢ÉúÑĵ½sessionÖС£
½«ÖÐÑë¼þ×¢²áµ½Â·ÓÉÖÐ
ÔÚroutes/web.phpÎļþÖУ¬×¢²á·ÓɺÍÖÐÑë¼þ£¬´úÂëÈçÏ£º
Route::get('/dashboard', function () { return view('dashboard'); })->middleware([LogMiddleware::class, AuthMiddleware::class]);
µÇ¼ºó¸´ÖÆ
ÉÏÃæµÄ´úÂ뽨ÉèÁËÒ»¸öÃûΪdashboardµÄ·ÓÉ£¬ÔÚdashboard·ÓÉÖУ¬Ê¹ÓÃÁËLogMiddlewareºÍAuthMiddlewareÖÐÑë¼þ¡£
ʵÏÖÖÐÑë¼þÌøת
Ö±½Ó»á¼ûhttp://yourdomain/dashboardÒ³Ãæʱ£¬½«»á×Ô¶¯Ìøתµ½http://yourdomain/login£¬²¢ÔÚsessionÖÐÉúÑÄÓйýʧÐÅÏ¢¡£
¶þ¡¢×ܽá
ÔÚLaravel 5.4ÖУ¬ÎÒÃÇ¿ÉÒÔʹÓÃredirect()º¯ÊýºÍwith()º¯ÊýÀ´ÊµÏÖÖÐÑë¼þÌøת¡£Í¨¹ýÒÔÉÏ°ì·¨£¬ÎÒÃÇÀֳɵØʵÏÖÁËÒ»ÆäÖÐÑë¼þÌøת¹¦Ð§¡£Ï£Íû±¾ÎÄÄܶÔÄãÓÐËù×ÊÖú£¡
ÒÔÉϾÍÊÇÔõÑùÔÚLaravel 5.4ÖÐʵÏÖÖÐÑë¼þÌøתµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡