简体   繁体   English

laravel政策授权永远是假的

[英]laravel policy authorize always false

I'm trying to allow users editing their own review in Laravel 5.5 我试图允许用户在Laravel 5.5中编辑他们自己的评论

AuthServiceProvider.php 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 ReviewPolicy.php

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

ReviewController.php 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());

}

I keep getting 我一直在

Symfony \\ Component \\ HttpKernel \\ Exception \\ AccessDeniedHttpException This action is unauthorized. Symfony \\ Component \\ HttpKernel \\ Exception \\ AccessDeniedHttpException此操作未经授权。

When in fact it should be authorized 实际上它应该被授权

I am probably missing something but I can't find what. 我可能错过了一些东西,但我找不到什么。

The problem is model binding doesn't work because $review is empty. 问题是模型绑定不起作用,因为$review是空的。 To make it work the route should look like this: 要使其工作,路线应如下所示:

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

Or, you could fetch the review manually: 或者,您可以手动获取评论:

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());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM