Validation Request – Laravel 5.1, how to handle validation on update?

Access all tutorials in sprocket icon.

May 24, 2015 from author Bill Keck.

Here is the quick answer for anyone who might be wondering how to handle validation on update in Laravel 5.  It seems like this is a common question, with lots of answers with verbose code.

However the solution is quite simple and concise.

The problem you can run into is that the validator requires the DB column to hold unique values, but when you are updating, you can’t pass validation unless you change the value for that field and you might not want to do that.

We’re going to look at this in the context of a request class, which  you would typically make to handle the validation rules for a form.  It’s a really cool feature of Laravel 5.

Inside the rules, you will have something like the following:

return [
    'name' => 'required|unique:mytablename,name,' . $this->mywildcard,
    'description' => 'required',
    'category' => "required|in:$range"

Ok, the basic validator rules you should be familiar with, if not check the guide.  

In the example above, we are supposing you want to store a name field in a table, generically referenced above as mytablename.  Obviously you will substitute that for the table where you store the name field, for example, if it were the users table, then it would be unique:users,name,

In order for this to work properly, we need to concatenate the id of the record, which is handed in through the route wildcard.  I’m just calling it mywildcard, in your case it could be id or any number of other things.  You just need to know it’s the value coming in from the route.

We use keyword $this, for example, $this->mywildcard or $this->id, etc., because the request object has this value.

Also note that the validation rule is within the single quotes and the id of the record is concatenated onto that outside of that string.  And that’s pretty much it. Laravel 5 does the rest.

I hope you have enjoyed this tutorial and found it useful. Click on the sprocket icon at the top of the page to see all tutorials. Please comment, share, and like if you can, thanks!

I don’t have a donate button, but If you would like to support my work and learn more about Laravel, you can do so by buying one of my books, Laraboot: laravel 5* For Beginners, I really appreciate it.