ÔõÑùʹÓÃLaravelÀ´ÑéÖ¤Óû§ÊÇ·ñµÇ¼
laravel ÊÇÏÖÔÚ×îÊ¢ÐÐµÄ php ¿ò¼ÜÖ®Ò»¡£ËüÌṩÁËÐí¶àÊÊÓù¤¾ßºÍº¯Êý£¬Ê¹¿ª·¢Ö°Ô±Äܹ»¿ìËÙ¹¹Á¢¹¦Ð§Ç¿Ê¢µÄ web Ó¦ÓóÌÐò¡£ÔÚÐí¶à web Ó¦ÓóÌÐòÖУ¬Óû§ÐèÒªµÇ¼£¬ÒÔ±ã»á¼ûÊܱ£»¤µÄÒ³Ã棬ÎÒÃÇÐèҪѧϰÔõÑùʹÓà laravel À´ÑéÖ¤Óû§ÊÇ·ñµÇ¼¡£
ÔÚ Laravel ÖУ¬Óû§ÈÏ֤ϵͳÊÇÓɹٷ½µÄ Laravel Auth ¾ÙÐÐÖÎÀíµÄ£¬Õâ¸öϵͳÌṩÁËÐí¶à³£¼ûµÄÈÏÖ¤¹¦Ð§£¬ÀýÈçÓû§×¢²á¡¢µÇ¼ºÍÃÜÂëÖØÖõȡ£ÔÚÕâ¸öϵͳÖУ¬ÎÒÃÇʹÓà Middleware À´ÑéÖ¤Óû§ÊÇ·ñÒѾµÇ¼¡£Middleware ÊÇÒ»¸öÇëÇó¹ýÂËÆ÷£¬ÓÃÓÚÔÚÇëÇóµÖ´ïÖ¸¶¨Â·ÓÉ֮ǰִÐÐһЩ²Ù×÷¡£ÎÒÃÇ¿ÉÒÔʹÓà Middleware À´ÑéÖ¤Óû§ÊÇ·ñÒѾµÇ¼£¬ÒÔ±ãÎÒÃÇÄܹ»ÏÞÖÆÓû§»á¼ûÊܱ£»¤µÄÒ³Ãæ¡£
ÏÂÃ棬ÎÒ½«ÏòÄãչʾÔõÑùʹÓà Middleware À´ÑéÖ¤Óû§ÊÇ·ñÒѾµÇ¼¡£ÎÒÃÇ¿ÉÒÔʹÓà Laravel ×Ô´øµÄ make:middleware ÏÂÁîÀ´½¨ÉèÒ»¸öÐ嵀 Middleware£¬ºÃ±ÈÎÒÃÇ¿ÉÒÔ½¨ÉèÒ»¸öÃûΪ “AuthMiddleware” µÄÖÐÑë¼þ¡£
ÎÒÃÇ¿ÉÒÔÔËÐÐÒÔÏÂÏÂÁîÀ´½¨Éè AuthMiddleware£º
php artisan make:middleware AuthMiddleware
µÇ¼ºó¸´ÖÆ
ÔËÐÐÉÏÊöÏÂÁîºó£¬Laravel »áÔÚ app/Http/Middleware Ŀ¼Öн¨ÉèÒ»¸ö AuthMiddleware.php Îļþ¡£´Ëʱ£¬ÎÒÃÇÐèÒªÔÚÕâ¸öÎļþµÄ handle ÒªÁìÖбàдÎÒÃǵÄÑéÖ¤Âß¼¡£ÏÂÃæÊÇÒ»¸öʾÀý£º
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\Auth; class AuthMiddleware { public function handle($request, Closure $next) { if (!Auth::check()) { return redirect('/login'); } return $next($request); } }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄÀý×ÓÖУ¬ÎÒÃÇÊ×ÏÈʹÓà Auth::check() ÒªÁìÀ´¼ì²éÓû§ÊÇ·ñÒѾµÇ¼¡£ÈôÊÇÓû§Ã»ÓеǼ£¬ÎÒÃǽ«Öض¨Ïòµ½ /login Ò³Ãæ¡£ÈôÊÇÓû§ÒѾµÇ¼£¬ÎÒÃǽ«ÔÊÐíÇëÇó¼ÌÐøÖ´ÐУ¬Õâ¾ÍÊÇÎÒÃÇËùνµÄ¡¸Í¨¹ý Middleware¡¹¡£
ÏÂÒ»²½£¬ÎÒÃÇÐèÒªÔÚÎÒÃǵÄ·ÓÉÖÐʹÓà AuthMiddleware¡£ÎÒÃÇ¿ÉÒÔÔÚ Laravel µÄ·Óɽç˵ÖÐʹÓà Middleware µÄ·½·¨ÓÐÁ½ÖÖ£º
ÒªÁìÒ»£ºÔÚ·Óɽç˵ÖÐʹÓà Middleware
Route::get('/dashboard', function () { return view('dashboard'); })->middleware('auth');
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÊö´úÂëÖУ¬ÎÒÃÇʹÓà auth ÖÐÑë¼þÀ´ÑéÖ¤Óû§ÊÇ·ñÒѾµÇ¼¡£µ±Óû§»á¼û /dashboard Ò³Ãæʱ£¬ÈôÊÇÓû§Ã»ÓеǼ£¬Ëü½«±»Öض¨Ïòµ½ /login Ò³Ãæ¡£
ÒªÁì¶þ£ºÔÚ¿ØÖÆÆ÷ÀàÖÐʹÓà Middleware
namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class DashboardController extends Controller { public function __construct() { $this->middleware('auth'); } public function index() { return view('dashboard'); } }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÊö´úÂëÖУ¬ÎÒÃÇÔÚ¿ØÖÆÆ÷ÖÐʹÓà AuthMiddleware£¬µ±Óû§»á¼û /dashboard ʱ£¬ÈôÊÇÓû§Ã»ÓеǼ£¬Ëü½«±»Öض¨Ïòµ½ /login Ò³Ãæ¡£
ÏÖÔÚ£¬ÎÒÃÇÒѾѧ»áÁËÔõÑùʹÓà Laravel À´ÑéÖ¤Óû§ÊÇ·ñÒѾµÇ¼£¬ÎÒÃÇ¿ÉÒÔÔÚ¿ØÖÆÆ÷ºÍ·ÓÉÖÐʹÓà Middleware£¬ÒÔ±ãÏÞÖÆÓû§»á¼ûÊܱ£»¤µÄÒ³Ã档ͨ¹ý Middleware£¬ÎÒÃÇ¿ÉÒÔÈÃÎÒÃǵÄÓ¦ÓóÌÐòÔ½·¢Çå¾²ºÍ¿É¿¿¡£
ÒÔÉϾÍÊÇÔõÑùʹÓÃLaravelÀ´ÑéÖ¤Óû§ÊÇ·ñµÇ¼µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡