ÁÄÁÄLaravelÖеÄȨÏÞÒªÁì
laravelÊÇÒ»¸öºÜÊÇÊ¢ÐеÄphp¿ò¼Ü£¬ÓµÓÐÖÚ¶àµÄ±ãµ±¹¦Ð§¡£ÆäÖаüÀ¨Ò»¸öÃûΪ¡°È¨ÏÞ¡±µÄÌØÕ÷¡£ÔÚlaravelÖУ¬È¨ÏÞ¿ÉÒÔ×ÊÖú¿ª·¢ÕßΪËûÃǵÄÓ¦ÓóÌÐò½¨ÉèÒ»¸ö»á¼û¿ØÖÆϵͳ£¬È·±£Ö»ÓÐÊÚȨÓû§²Å»ª»á¼ûÌض¨µÄapi¶Ëµã¡¢Ò³Ãæ»ò²Ù×÷¡£½ÓÏÂÀ´£¬ÎÒÃǽ«ÏÈÈÝlaravelÖеÄȨÏÞÒªÁì¡£
½ÇÉ«ºÍȨÏÞ
ÔÚLaravelÖУ¬È¨Ï޺ͽÇÉ«ÊÇÏà¹ØÁªµÄ¿´·¨¡£½ÇÉ«ÊÇÖ¸²î±ðµÄÓû§ÀàÐÍ£¬ËûÃDzî±ðµÄ½ÇÉ«¿ÉÒÔ»á¼ûÓ¦ÓóÌÐòÖеIJî±ð²¿·Ö¡£È¨ÏÞÖ¸µÄÊÇ¿ØÖÆÓû§¿É»á¼ûÄÄЩ²¿·ÖµÄ¹æÔò¡£
ÔÚLaravelÖУ¬½ÇÉ«¿ÉÒÔͨ¹ýÏÂÁîÐй¤¾ßartisanÀ´½¨Éè¡£ÀýÈ磬ÎÒÃÇ¿ÉÒÔ½¨ÉèÒ»¸öÃûΪ¡°ÖÎÀíÔ±¡±µÄ½ÇÉ«£¬Ê¹ÓÃÒÔϵÄartisanÏÂÁ
php artisan make:role admin
µÇ¼ºó¸´ÖÆ
ÀàËƵأ¬ÎÒÃÇ¿ÉÒÔ½¨ÉèÒ»¸öÃûΪ¡°Îı¾±à¼Æ÷¡±µÄ½ÇÉ«£º
php artisan make:role editor
µÇ¼ºó¸´ÖÆ
È»ºó£¬ÎÒÃǾͿÉÒÔ½«ÕâЩ½ÇÉ«·ÖÅɸøÓû§¡£
ÊÚȨ
ÔÚLaravelÖУ¬ÎÒÃÇ¿ÉÒÔʹÓÃÊÚȨÀ´ÏÞÖÆÓû§»á¼ûÓ¦ÓóÌÐòÖеIJî±ð²¿·Ö¡£ÊÚȨ¿ÉÒÔÔÚ¿ØÖÆÆ÷Öнç˵£¬È·±£Ö»ÓÐÊÚȨÓû§²Å»ªÖ´ÐÐÌض¨µÄ²Ù×÷¡£
ÀýÈ磬ÎÒÃÇ¿ÉÒÔ½¨ÉèÒ»¸öÃûΪ¡°AdminUsersController¡±µÄ¿ØÖÆÆ÷£¬¸Ã¿ØÖÆÆ÷ÔÊÐíÖ»ÓÐÖÎÀíÔ±Óû§»á¼û£º
php artisan make:controller AdminUsersController
µÇ¼ºó¸´ÖÆ
½ÓÏÂÀ´£¬ÎÒÃÇÐèÒªÔÚ¿ØÖÆÆ÷µÄ½á¹¹º¯ÊýÖнç˵ÊÚȨ×é¼þ£º
public function __construct() { $this->authorize('admin'); }
µÇ¼ºó¸´ÖÆ
µ±Ã»ÓÐÊÚȨÓû§ÊµÑé»á¼û¸Ã¿ØÖÆÆ÷ʱ£¬½«Å׳öÒ»¸öÒì³£¡£ÎÒÃÇ¿ÉÒÔÔÚLaravelµÄExceptionHandlerÖнç˵Òì³£´¦Àí³ÌÐò¡£
ȨÏÞ±í
ÔÚLaravelÖУ¬ÎÒÃÇ¿ÉÒÔ½¨ÉèÒ»¸öÃûΪ¡°permissions¡±µÄ±í£¬ÓÃÀ´´æ´¢Ó¦ÓóÌÐò¹¦Ð§µÄȨÏÞ¡£¿ÉÒÔʹÓÃÒÔÏÂÏÂÁîÐй¤¾ßartisan½¨ÉèȨÏÞ±í£º
php artisan make:model Permission -m
µÇ¼ºó¸´ÖÆ
Õ⽫»áÌìÉúÒ»¸öÃûΪ¡°Permission¡±µÄÄ£×ÓÎļþºÍÒ»¸öÓëÖ®Ïà¹ØµÄǨáãÎļþ¡£
Ä£×ÓÎļþÖаüÀ¨Ò»¸öÃûΪ¡°role¡±µÄÒªÁ죬¿ÉÒÔÈÃÎÒÃÇ¿ìËÙ»ñÈ¡Óë½ÇÉ«Ïà¹ØÁªµÄȨÏÞ£º
public function roles() { return $this->belongsToMany(Role::class); }
µÇ¼ºó¸´ÖÆ
È»ºó£¬ÎÒÃÇ¿ÉÒÔÔÚÄ£×ÓÎļþÖнç˵í§ÒâÊýÄ¿µÄȨÏÞ¡£
ÊÚȨ¹æÔò¿ÉÒÔÓÉÓ¦ÓóÌÐòÖеÄÖÎÀíÔ±Óû§Í¨¹ýÏÂÁîÐÐÔËÐÐartisanÀ´½¨ÉèºÍÖÎÀí¡£½ÓÏÂÀ´£¬ÎÒÃÇÀ´¿´¿´ÔõÑùÏÖʵӦÓÃÕâЩÊÚȨ¹æÔò¡£
ÊÚȨÃÅÃæ
ÔÚLaravelÖУ¬ÎÒÃÇ¿ÉÒÔʹÓÃÊÚȨÃÅÃæÀ´¼ò»¯ÊÚȨµÄʹÓá£Ê¹ÓÃÃÅÃ棬ÎÒÃÇ¿ÉÒÔÇáËɵؼì²éÄ¿½ñµÇ¼µÄÓû§ÊÇ·ñÓÐȨÏÞ»á¼û²Ù×÷»ò×ÊÔ´¡£
ÀýÈ磬ÎÒÃÇ¿ÉÒÔʹÓá°Gate¡±ÃÅÃæÀ´¼ì²éÄ¿½ñÓû§ÊÇ·ñÓµÖøÃûΪ¡°edit-post¡±µÄȨÏÞ£º
if (Gate::allows('edit-post', $post)) { // Óû§ÓÐȨ±à¼Ìû×Ó }
µÇ¼ºó¸´ÖÆ
ÎÒÃÇ»¹¿ÉÒÔͨ¹ý¡°Gate¡±ÃÅÃæÀ´½ç˵еÄÊÚȨ¹æÔò£¬ÒÔÖ§³ÖÎÒÃÇÓ¦ÓóÌÐòµÄÌض¨ÐèÇó£º
Gate::define('update-post', function ($user, $post) { return $user->id === $post->user_id; });
µÇ¼ºó¸´ÖÆ
ÔÚÕâ¸öÀý×ÓÖУ¬ÎÒÃǽç˵ÁËÒ»¸öеÄÊÚȨ¹æÔò£¬Ê¹µÃÖ»ÓÐPostµÄËùÓÐÕß²ÅÓÐȨ¸üÐÂËü¡£
LaravelµÄȨÏÞϵͳÊÇÒ»¸öºÜÊÇÀû±ãµÄ¹¦Ð§£¬ÈÃÓ¦ÓóÌÐò¿ª·¢ÕßÇáËɵØÕÆ¿ØÊÚȨÓû§¿ÉÒÔ»á¼ûÄÄЩ²¿·Ö»ò²Ù×÷¡£Í¨¹ýʹÓýÇÉ«ºÍȨÏÞ£¬ÎÒÃÇ¿ÉÒÔÈÝÒ׵ؽ¨ÉèÒ»¸öÇ¿Ê¢¶øÖØ´óµÄ»á¼û¿ØÖÆϵͳ¡£
×ÜÖ®£¬Laravel¿ò¼ÜÌṩÁËÒ»ÖÖ¼òÆÓ¶øÇ¿Ê¢µÄÒªÁìÀ´ÊµÏÖȨÏÞÖÎÀí£¬Ê¹µÃÓ¦ÓóÌÐòµÄ¿ª·¢Õß¿ÉÒÔ¸üÈÝÒ׵ؽç˵ºÍÖÎÀíÓû§½ÇÉ«ÒÔ¼°Æä»á¼ûȨÏÞ£¬´Ó¶ø¸üºÃµØÕÆ¿ØÕû¸öÓ¦ÓóÌÐòµÄÇå¾²ÐÔ¡£
ÒÔÉϾÍÊÇÁÄÁÄLaravelÖеÄȨÏÞÒªÁìµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡