我让它运转起来 . 我一直在收到 This action is unauthorized
,我也尝试过使用路由中间件 .
PagePolicy.php
:
namespace App\Policies;
use App\Models\User;
use App\Models\Page;
use Illuminate\Auth\Access\HandlesAuthorization;
class PagePolicy
{
use HandlesAuthorization;
/**
* Determine whether the user can view the page.
*
* @param App\Models\User $user
* @param App\Models\Page $page
* @return mixed
*/
public function view(User $user, Page $page)
{
return $user->id === $page->user_id;
}
/**
* Determine whether the user can create pages.
*
* @param App\Models\User $user
* @return mixed
*/
public function create(User $user)
{
}
/**
* Determine whether the user can update the page.
*
* @param App\Models\User $user
* @param App\Models\Page $page
* @return mixed
*/
public function update(User $user, Page $page)
{
//
}
/**
* Determine whether the user can delete the page.
*
* @param App\Models\User $user
* @param App\Models\Page $page
* @return mixed
*/
public function delete(User $user, Page $page)
{
//
}
}
PageController.php
:
namespace App\Http\Controllers;
use Auth;
use Carbon\Carbon;
use App\Models\Page;
use App\Http\Requests\PageRequest;
class PageController extends ApiController
{
public function createNewPage(PageRequest $request)
{
$this->authorize('create', Page::class);
$request->merge([
'user_id' => Auth::id(),
'published_at' => Carbon::now(),
]);
if (Page::create($request->all())) {
return response()->json('success', 201);
}
return response()->json('error', 500);
}
}
AuthServiceProvidor.php
:
namespace App\Providers;
use App\Models\Page;
use App\Policies\PagePolicy;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
Page::class => PagePolicy::class,
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
//
}
}
4 回答
当前代码:
解决方案代码
我在Laravel网站上关注Intermediate Task List Tutorial时遇到了同样的问题 .
该解决方案实际上存在于Github code for this tutorial中 .
我设法搞清楚了 . 我没有使用Route Model Binding . 所以我在页面调用后添加了
authorize()
并使用了$page
变量而不是Page::class
.由于您已经提供了在控制器中创建的调用但仅提供了用于查看页面的策略检查,因此我不完全清楚您尝试授权的操作 . 话虽如此,我确定var_dump / dd你试图进行类型比较的值,以验证它们是同一类型 . 如果显式转换了任何内容,则可能会导致将某些整数作为字符串返回的某些数据库驱动程序出现问题 .
我认为问题不在你的政策中,而在你的
PageRequest
课程中 . 确保App\Http\Requests\PageRequest
类中的authorize()
方法返回true
.