Home > database >  Laravel livewire route model binding validation limitation
Laravel livewire route model binding validation limitation

Time:07-08

Just trying to validate fields in a Livewire component using Route Model Binding feature. When defining rules in specific function (required in docs for Route Model Binding to work), defining, e.g., a unique rule translates in a database error as the post.message field obviously does not exist:

...
protected function rules()
{
    return [
        'post.message' => [
                           'required', 
                           'string', 
                           Rule::unique('posts')
                            ->where(function ($query) { return $query->where('user_id', Auth::id()); })
                            ->ignore($this->post->id)
                          ],
        ...
   ]
   ...
}

And the obvious error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'post.message' in 'where clause'
select
  count(*) as aggregate
from
  `posts`
where
  `post`.`message` = Hello
  and `id` <> 1
  and (`user_id` = 2)

Any ideas on how to implement it? Thanks in advance.

CodePudding user response:

Just for the record, I found the solution. My fault, perhaps if I was looked better at the docs, I wouldn't have had this problem (like many other times I'm afraid).

As stated in the docs, the unique rule of the Rule object lets specifying the specific column of the database to search in through a second parameter, so the solution was to simply add that parameter to the rule:

Rule::unique('posts', 'message')->where(function ($query)...

Thanks again.

  • Related