In Laravel the unique
validation rule will trigger even when you are updating the original record, unless you provide some logic
in your FormRequest
to exclude the record when updating. This trait can be used to avoid that logic by detecting when a record is being created or updated.
Place the trait in app\Http\Traits
(if using a different directory simply change the namespace) and then use it inside your form request or add it to the app\Requests\Request.php
:
use App\Http\Traits\ValidationHelper
You can now do as follows in your FormRequest:
public function rules()
{
return [
'email' => [$this->unique('users','email')]
];
}
This will now automatically exclude the original record from the unique check when it is being updated.
The unique function takes the following parameters:
$table The name of the table we are using the unique rule on.
$column - The column that should be unique.
$id - The name of the primary key (defaults to id).
$where - The where parameters passed as an associative array e.g. ['account_id' => 1]
$routeParameterName - The route parameter name for the update. Only needs to be specified if you have multiple route parameters
$ignoreExclusionRule - Set to true to avoid excluding any records when updating. When set to true it's same as using 'unique:table,column' and is only included for consistency purposes.
Note: This trait pulls the excluded id directly from the route. If you only have one route parameter e.g. /admin/users/{user_id}/edit
then the value of {user_id}
will automatically be used in the exclude rule
. You only need to specifiy the $routeParameterName
if you are using multiple paramaters in your route e.g. /my/route/{param1}/{param2}
, In this case to exclude param2
you would pass 'param2'
as the $routeParameterName
.
The trait supports route model binding, there is no need to make any adjustments if you are binding your models to your routes.
public function rules()
{
return [
'email' => [$this->unique('users','email', 'id', ['account_id' => 1], 'user_id')]
];
}