Validating Unique Records Using Laravel Form Requests

  • May 05, 2015

Welcome to the incredibly popular Easy Laravel 5 companion blog. To celebrate the new edition's release (updated for Laravel 5.5!) use the discount code easteregg to receive 20% off the book or book/video package! » Buy the book

When building web applications there are plenty of situations in which you'll want to make sure a database table field contains only unique values. For instance if you're creating a product catalog then logically each product's SKU should be unique. Laravel's Validation class has long supported a unique validator for ensuring a given field is unique, but the introduction of form requests in Laravel 5 has caused some confusion in terms of how form request rules method can be used in conjunction with the unique validation rule when editing a record, so I thought I'd put together a quick example demonstrating how the two are used together.

Suppose you were validating a product management form used in conjunction with a product catalog manager. Each product consists of three required fields: a product name, SKU, and price. Further, each product SKU must be unique. While it's enough to simply specify required when validating a required field, the unique validator is a tad more involved because if you're editing a product (for instance, changing the price), and don't additionally change the SKU, Laravel will generate an error informing you that the SKU already exists. Indeed it does; it's associated with the very record you're trying to edit! To resolve this dilemma, you additionally need to identify three other pieces of information as presented in the following rules method:

public function rules()
    return [
      'name'  => 'required',
      'sku'   => 'required|unique:products,sku,' . $this->get('id'),
      'price' => 'required|numeric'

These three additional pieces of information include:

  • The database table: In this example, that table is products.
  • The column name: In this example, table column name is sku.
  • The ignored primary key: This is the crucial part. In this example we're identifying the id passed along with the rest of the form information. This id is the record's primary key. When specified, the unique validator will examine all other records, but ignore the record associated with this ID.

With this additional information in place, you're ready to begin using form requests in conjunction with the unique validator!