Skip to content

Instantly share code, notes, and snippets.

@EduardoSP6
Last active February 25, 2019 18:19
Show Gist options
  • Save EduardoSP6/b7fe9193d1f447b1c9bb33afaf77d3ce to your computer and use it in GitHub Desktop.
Save EduardoSP6/b7fe9193d1f447b1c9bb33afaf77d3ce to your computer and use it in GitHub Desktop.
Laravel 5.4 validation rule unique in Request
# Valid field serial_number from model Product as unique as an example;
# Note if we are updating the record, and the value of record field is equals to value of request (received from form submit),
it's necessary ignore because didn't have alterations in this field. Otherwise, it will validate as unique field.
class ProductRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
switch ($this->method()) {
case 'GET': {
return [];
}
case 'DELETE': {
return [];
}
case 'POST': {
return [
'fire_stamp' => 'required|unique:products,serial_number',
];
}
case 'PUT': {
return [
'fire_stamp' => $this->product->serial_number == $this->get('serial_number') ? Rule::unique('products')->ignore($this->get('serial_number'), 'serial_number') : 'required|unique:products,serial_number',
];
}
default:
break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment