我试图允许用户在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 此操作未经授权。
实际上它应该被授权
我可能错过了一些东西,但我无法找到。
答案 0 :(得分:2)
问题是模型绑定不起作用,因为$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());
}