App\Http\Requests\Comment\CreateRequest::authorize() 的声明应该与 App\Http\Requests\Request::authorize() 兼容

Declaration of App\Http\Requests\Comment\CreateRequest::authorize() should be compatible with App\Http\Requests\Request::authorize()

你好,我正在为我的 laravel 应用程序创建评论系统,但是当我尝试评论时出现此错误。基本上当用户未登录并且他尝试评论并提交时,它应该将他重定向到登录页面,所以我的 CreateRequest 文件是这样的

<?php

namespace App\Http\Requests\Comment;

use App\Http\Requests\Request;
use App\Repositories\Image\ImageRepository;

class CreateRequest extends Request {
    /**
     * Determine if the user is authorized to make this request.
     *
     * @param ImageRepository $image
     * @return bool
     */
    public function authorize(ImageRepository $image) {
        $image = $image->getById($this->route('id'))->first();
        if (!$image) {
            return false;
        }
        return auth()->check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules() {
        return [
            'comment' => ['required', 'min:2'],
        ];
    }

    /**
     * @return \Illuminate\Http\RedirectResponse
     */
    public function forbiddenResponse() {
        return redirect()->route('login');
    }
}

我的 App\Http\Requests\Request 文件是这个

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

abstract class Request extends FormRequest {
    public function authorize() {
        return true;
    }
}

如果我删除

public function authorize() {
    return true;
}

然后评论有效,如果用户未登录,用户将被重定向到登录页面,但我的登录不起作用,当我尝试登录时我被禁止

我在这个项目的基础上开发我的应用程序 https://github.com/laravelish/EasyAdmin 希望有人能帮助我

您在抽象请求中定义了一个 authorize 方法 class:

public function authorize() {
    return true;
}

请注意,它不带任何参数。现在,如果您扩展此抽象 class(就像您使用 CreateRequest 所做的那样)并编写一个 authorize 方法,则您 必须 使用相同的签名。具体来说:authorize不能带任何参数,因为它在抽象中没有class.


如果您要从抽象 class 中删除 authorize 方法,这个特定错误就会消失。但是我不确定这会解决您的问题。我不认为 Laravel 为 authorize 方法提供依赖注入,你不能像那样注入你的存储库。

这是解决这两个问题的一种方法:

public function authorize() {
    $image = app(ImageRepository::class)->getById($this->route('id'))->first();
    ...