Framework: Validating a nested attribute against the 'unique:table' rule would throw a QueryException

Created on 7 Nov 2018  路  3Comments  路  Source: laravel/framework

  • Laravel Version: 5.7.12
  • PHP Version: 7.2.9
  • Database Driver & Version: mysqlnd 5.0.12-dev

Description:

From the docs:
"A Note On Nested Attributes
If your HTTP request contains 'nested' parameters, you may specify them in your validation rules using 'dot' syntax".

Applying the unique:table_name rule on a nested parameter throws a \Illuminate\Database\QueryException.

Steps To Reproduce:

dd($request->all());
Received parameters:

array:3 [
  "role" => array:2 [
    "name" => "my role"
    "active" => 1
  ]
  "permissions" => array:1 [
    0 => array:4 [
      "module" => "my module"
      "view" => 1
      "edit" => 1
      "delete" => 1
    ]
  ]
  "token" => "random hash"
]

Validating the name attribute:
$request->validate(['role.name' => 'required|unique:roles']);

Exception:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'role.name' in 'where clause' (SQL: select count(*) as aggregate from `roles` where `role`.`name` = my role)

The dot composition 'role.name' in this case is not parsed accordingly and passed entirely as one sql query parameter which mysql interpret as the column name 'role.name'.

Most helpful comment

From the documentation:

If the column option is not specified, the field name will be used.

In your case, this is role.name. Specify a custom column name:

$request->validate(['role.name' => 'required|unique:roles,name']);

All 3 comments

From the documentation:

If the column option is not specified, the field name will be used.

In your case, this is role.name. Specify a custom column name:

$request->validate(['role.name' => 'required|unique:roles,name']);

Thanks for helping @staudenmeir.

@staudenmeir Thank you! I missed that 馃槄 I clearly need to review the docs 馃憤

Was this page helpful?
0 / 5 - 0 ratings

Related issues

JamborJan picture JamborJan  路  3Comments

RomainSauvaire picture RomainSauvaire  路  3Comments

YannPl picture YannPl  路  3Comments

gabriellimo picture gabriellimo  路  3Comments

Anahkiasen picture Anahkiasen  路  3Comments