gpt4 book ai didi

php - 无法在 Laravel 5.3 中使用策略

转载 作者:可可西里 更新时间:2023-11-01 01:15:39 27 4
gpt4 key购买 nike

我一直在关注 Laravel 授权文档,试图通过使用策略构建“用户是否被允许执行此操作”功能,但我无法让它工作。我不断收到 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();

//
}
}

最佳答案

我设法弄清楚了。我没有使用路由模型绑定(bind)。所以我在页面调用之后添加了 authorize() 并使用了 $page 变量而不是 Page::class

public function update(PageUpdateRequest $request, $pageSlug)
{
$page = Page::where(['user_id' => Auth::id(), 'slug' => $pageSlug])->first();
$this->authorize('update', $page);
$page->update($request->all());
return fractal()->item($page, new PageTransformer())->toArray();
}

关于php - 无法在 Laravel 5.3 中使用策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39427393/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com