gpt4 book ai didi

php - 策略始终导致 "This action is unauthorized"

转载 作者:行者123 更新时间:2023-12-05 09:06:27 29 4
gpt4 key购买 nike

我试图让用户在 Laravel 8 中查看类别页面

CategoryPolicy.php


use App\Models\Category;
use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;

class CategoryPolicy
{
use HandlesAuthorization;

/**
* Determine whether the user can view any models.
*
* @param User $user
* @return mixed
*/
public function viewAny(User $user)
{

return true;
}

}

Category.php 模型

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
use HasFactory;

protected $fillable = ['category_name','category_image', 'parent_category'];

public function categories (): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(Category::class, 'parent_category');
}


public function parentCategory (): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(Category::class, 'parent_category');
}

}

在 AuthServiceProvider.php 中注册策略

    protected $policies = [
Category::class => CategoryPolicy::class
];

路线

Route::group(['middleware' => 'auth'], function () {
Route::get('/', [DashboardController::class, 'index']);
Route::get('/admin', [DashboardController::class, 'index']);
Route::get('/admin/categories', [CategoryController::class, 'categories'])->name('category.index');
Route::get('/admin/get-categories', [CategoryController::class, 'allCategories'])->name('category.indexAjax');
Route::get('/admin/get-all-categories', [CategoryController::class, 'getCategories'])->name('category.all');
Route::post('/admin/category/new', [CategoryController::class, 'store'])->name('category.new');
Route::delete('/admin/category/delete/{category}', [CategoryController::class, 'delete'])->name('category.delete');
});

类别 Controller


class CategoryController extends Controller
{

public function categories(Request $request)
{
$this->authorize('viewAny');
return view('admin.categories.categories');
}

public function getCategories(Request $request)
{
$categories = Category::all();
return Response::json([
"success" => true,
"data" => $categories
]);
}


public function allCategories(Request $request)
{
return DataTables::of(Category::with('parentCategory')->get())->addIndexColumn()->make(true);
}
}

这总是返回“403 此操作未经授权。”

我的代码应该可以工作......是的......它没有,这让我发疯。

谢谢

最佳答案

您应该使用授权方法发送模型

试试这个:

$this->authorize('viewAny', Category::class);

来自文档:https://laravel.com/docs/8.x/authorization#via-controller-helpers

关于php - 策略始终导致 "This action is unauthorized",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66071720/

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