我正在了解Laravel 5.3中的政策,我遇到了问题,它总是返回“此操作未经授权”。我究竟做错了什么?以下是代码:
UserController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class UserController extends Controller
{
public function index()
{
$this->authorize('list');
$users = User::all();
return $users;
}
}
AuthServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
protected $policies = [
'App\User' => 'App\Policies\UserPolicy',
];
public function boot()
{
$this->registerPolicies();
}
}
UserPolicy.php
<?php
namespace App\Policies;
use App\User;
use Illuminate\Auth\Access\HandlesAuthorization;
class UserPolicy
{
use HandlesAuthorization;
public function list(User $user)
{
return true;
}
}
答案 0 :(得分:1)
调用authorize
方法时,您需要在模型类中添加第二个参数集,否则laravel如何知道要检查授权的list
方法/策略?其他模型也可能具有list
方法/策略,因此需要第二个参数。
$this->authorize('list', User::class);