php - laravel 政策授权总是假的

标签 php laravel laravel-5

我试图让用户在 Laravel 5.5 中编辑他们自己的评论

AuthServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use App\Model\Review;
use App\Policies\ReviewPolicy;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
        Review::class => ReviewPolicy::class,
    ];

ReviewPolicy.php

public function update(User $user, Review $review)
{
    return $user->id == $review->user_id;
}

ReviewController.php

public function update(Request $request, Review $review ,int $id)
{
    $request->validate([
        'content' => 'required|min:250',
        'score' => 'numeric|min:0|max:10',
    ]);

    $this->authorize('update', $review);

    $reviewsSave = Review::find($id);
    $reviewsSave->content = $request->input('content');
    $reviewsSave->score = $request->input('score');
    $reviewsSave->save();

    return redirect(url()->current());

}

我不断得到

Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException 此操作未经授权。

实际上应该授权的时候

我可能遗漏了什么,但找不到。

最佳答案

问题是模型绑定(bind)不起作用,因为 $review 是空的。要使其正常工作,路线应如下所示:

Route::get('review/update/{review}/{id}', 'ReviewController@update');

或者,您可以手动获取评论:

public function update(Request $request, Review $review ,int $id)
{
    $request->validate([
        'content' => 'required|min:250',
        'score' => 'numeric|min:0|max:10',
    ]);

    $reviewsSave = Review::find($id);

    $this->authorize('update', $reviewsSave);

    $reviewsSave->content = $request->input('content');
    $reviewsSave->score = $request->input('score');
    $reviewsSave->save();

    return redirect(url()->current());
}

关于php - laravel 政策授权总是假的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48432594/

相关文章:

php - 如何在 Drupal 中为 Form API 按钮设置主题?

php - array_search bool 返回值

php - Laravel 基本路径

mysql - Laravel 急切加载与显式连接

javascript - Laravel-Mix 与 BrowserSync 可处理除 Vue.js 组件之外的所有内容

php - Laravel 5 如何在我看来正确使用设置变量

javascript - 复选框作为 yajra 数据表中的标题

php - SQL 统计表中的值,仅返回 5 个最高值

php - Laravel Query Builder 如何跳过并从最新到最旧的行?

php - Laravel 按类别对用户实体进行分组