I have some route/model binding set up in my project for one of my models, and that works just fine. I'm able to use my binding in my route path and accept an instance of my model as a parameter to the relevant method in my controller.

现在我正在try 使用这个模型做一些工作,所以我在我的控制器中创建了一个方法,它接受表单请求,这样我就可以执行一些验证.

public function edit(EditBrandRequest $request, Brand $brand)
{
    // ...

我的模型的每个不同实例都可以进行不同的验证,因此我需要能够使用模型的一个实例来构建一组自定义的验证规则.

Is there a way of getting the instance of the model, that is injected into the controller from the Form Request?

我try 在表单请求的构造函数中输入模型实例的类型提示

class EditBrandRequest extends Request
{
    public function __construct(Brand $brand)
    {
        dd($brand);
    }

我还try 过在表单请求的rules()方法中使用类型暗示模型实例.

class EditBrandRequest extends Request
{
    // ...

    public function rules(Brand $brand)
    {
        dd($brand);

In both instances I am provided an empty/new instance of the model, rather than the instance I am expecting.

Of course, I could always get around this by not bothering with Form Requests and just generate the rules in the controller and validate manually - but I would rather do it the Laravel way if it's possible.

谢谢

推荐答案

You can simply access it using the binding key, so for example if you bind Brand model: $router->model('brand', '\App\Brand') you can get instance of your model with $this->brand. Here is validation rules example:

'slug' => 'required|unique:brand,slug,' . $this->brand->id,

EDIT

Sometimes you might have an input name that uses the same name as the binding key, for example, if you bind Address model as address then you have an input field address it will make Laravel confuse. For this situation you can use route() method.

'address' => 'required|unique:addresses,address,' . $this->route('address')->id,

Laravel相关问答推荐

运行NPM Prod时出现VUE问题

Laravel 通过 API 嵌套 url 发布

如何正确使用 Spatie\Laravel Data 来获取数据?

如何避免谷歌翻译翻译:参数

无法在 Laravel 项目中安装 @vitejs/plugin-vue

Laravel init 查询多种用途

Laravel Debugbar 中的 Laravel api routes路由

Laravel Eloquent 查找日期超过 2 天的行

如何为路由 laravel 5 使用OR中间件

将 Laravel MYSQL 更改为 utf8mb4 以在现有数据库中支持表情符号

Laravel 5.4 LengthAwarePaginator

Laravel 验证 - 输入必须是数组中的项目之一

eloquent的搜索/自定义属性的位置

使用 ModelNotFoundException

设置 Laravel 5.4 以使用 React

使用 laravel eloquent 关系检索除 NULL 之外的所有记录

使用 Laravel 将两个模型合并到一个分页查询中,并带有Eager加载的关系

如何处理 php (Laravel api) 和 javascript (AngularJS) 之间的日期时间

将参数传递给 Laravel 中的中间件

Laravel 5 Illuminate\Http\Request 的方法不允许静态调用