Anda di halaman 1dari 44

pdfcrowd.com open in browser PRO version Are you a developer?

Try out the HTML to PDF API


Laravel Form
Validation
Chris Sevilleja July 8, 2014
forms, laravel, validation 15 Comments

PHP
Advertisements
Follow Follow Like
Q m _ V f
SCOTCH
BAR TALK TUTORI ALS SERI ES QUI CK TI PS PROJ ECTS ABOUT
pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
forms, laravel, validation 15 Comments
7
f
Share
21
V
Tweet
11
_
Plus
View Code
Today well be handling form validation in
Laravel. There are many things that need to
happen to make sure that everything works the
way a user would expect it to so lets get started.
Our Most Popular Articles
View All Popular
pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
Our application will do many things. These
include:
Validate required, unique in the database,
What Well Be
Building

View All Popular


pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
Validate required, unique in the database,
and matching form fields
Use Laravel to show errors
Use Laravel to show old inputs so a user
doesnt have to retype inputs
Create custom error messages
Thats a lot to do so lets get started. Well
start by setting up our database.
Once weve got Laravel all set up, lets go to
our command line and create our migration
so that our database table will be created.
Database and
Models

pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
We will need this so we can do validation to
make sure that emails entered are unique
in the database. We wouldnt want multiple
users with the same email right?
Migration
Go into the command line and type
$ php artisan migrate:make create_ducks_table --create=ducks
Now lets edit that newly generated
migration file.
Data Migration
Manage your Data Migration & Integration with 1 Platform.
pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
<?php
// app/database/migrations/####_##_##_######_create_ducks_table.php
use Illuminate\Database\Schema\Blueprint
use Illuminate\Database\Migrations\Migration
class CreateDucksTable extends Migration
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('ducks'
{
$table->increments
$table->string
$table->string
$table->string

$table->timestamps
});
}
}




21
23
pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
Now make sure your database settings are
good in app/config/local/database.php or
app/config/database.php and then lets run
our migration:
$ php artisan migrate
Model
We are going to create our Eloquent model
so that we can save our ducks to the
database. This is also how we will be able to
test to make sure that our new duck/user
has a unique email in the database.
Create the model at app/models/Duck.php .


pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
<?php
// app/models/Duck.php
class Duck extends Eloquent {
protected $fillable = array('name', 'email', 'password');
}
With our database and model ready to go,
now we can get to our actual validation.
Further Reading: A Guide to Using
Eloquent ORM in Laravel
Setting Up Our
pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
We will be handling the routing for our
application in the app/routes.php file that
Laravel provides. Well be handling the GET
for showing the form and the POST for
processing the form here.
<?php
// app/routes.php
// route to show the duck form
Route::get('ducks', function()
{
return View::make('duck-form');
});
// route to process the ducks form
Route::post('ducks', function()
{
// process the form here
});
Setting Up Our
Routes
pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
This will be accessible at
http://example.com/ducks and then well
also be POSTing to the same URL. With our
routes ready, lets create the duck-form
that we are displaying to our user.
Further Reading: Simple and Easy Laravel
Routing
The view file will be at
app/views/duck-form.blade.php and well
use Laravels Blade to handle our views. For
Creating Our View
pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
more information on Blade, heres a starter
Blade article.
Heres that view file. Well use Bootstrap to
make our views look good and then well
start our validation.
<!-- app/views/duck-form.blade.php -->
<!doctype html>
<html>
<head>
<title>Laravel Form Validation!</title>
<!-- load bootstrap -->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css
<style>
body { padding-bottom:40px; padding-top:40px; }
</style>
</head>
<body class="container">
<div class="row">
<div class="col-sm-8 col-sm-offset-2">

<div class="page-header">
<h1><span class="glyphicon glyphicon-flash"></span> Ducks Fly!</h1>
pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
</div>
<!-- FORM STARTS HERE -->
<form method="POST" action="/ducks" novalidate>
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" class="form-control" name="name
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" id="email" class="form-control" name="email
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" id="password" class="form-control" name
</div>
<div class="form-group">
<label for="password_confirm">Confirm Password</label>
<input type="password" id="password_confirm" class="form-control
</div>
<button type="submit" class="btn btn-success">Go Ducks Go!</button>
</form>
</div>
pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
</div>
</div>
</body>
</html>
Now our beautiful form has taken well
form.
pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
Now that we have our view, well be going
through all the validations needed. Since we
already have our forms action="/ducks"
ready to go, our form will send a POST
request to http://example.com/ducks and
then we handle that in the route we made
earlier in app/routes.php.
Lets start off our validation now in that
routes.php file. Were going to create our
rules, run the validation on the form inputs,
and handle the error messages from there.
Validating Our Form
Basic Form
Validation

pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
Creating Rules
Lets create those rules:
<?php
// app/routes.php
...
// route to process the ducks form
Route::post('ducks', function()
{
// process the form here
// create the validation rules ------------------------
$rules = array(
'name' => 'required', // just a normal required validation
'email' => 'required|email|unique:ducks', // required and must be unique in the ducks table
'password' => 'required',
'password_confirm' => 'required|same:password' // required and has to match the password field
);
// do the validation ----------------------------------
// validate against the inputs from our form
$validator = Validator::make(Input::all(), $rules);
pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
// check if the validator failed -----------------------
if ($validator->fails()) {
// get the error messages from the validator
$messages = $validator->messages();
// redirect our user back to the form with the errors from the validator
return Redirect::to('ducks')
->withErrors($validator);
} else {
// validation successful ---------------------------
// our duck has passed all tests!
// let him enter the database
// create the data for our duck
$duck = new Duck;
$duck->name = Input::get('name');
$duck->email = Input::get('email');
$duck->password = Hash::make(Input::get('password'));
// save our duck
$duck->save();
// redirect ----------------------------------------
// redirect our user back to the form so they can do it all over again
return Redirect::to('ducks');
}
pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
});
...
With this setup, we have:
A required name
A required email that has to be in email
form
An email that has to be unique in the
database
A required password
A password_confirm field that needs to
match password
So we have set the rules for our inputs. We
have run the validation and checked if that
worked. If it didnt work, we are sending our
user back to our form with the errors.
pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
If the validation succeeded, we are going to
create the duck in our database and
redirect the user back to the form.
For a full list of the validation rules available
to you, go look at the available validation
rules.
Lets say that our user did not pass the
validation. We want to show off all the
messages in our view. All we have to do is
go into our view and add that in.
Showing Errors In
the View

pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
Dumping Out All Error
Messages
<!-- app/views/duck-form.blade.php -->
...
<div class="row">
<div class="col-sm-8 col-sm-offset-2

<div class="page-header
<h1><span class
</div>
@if ($errors->has())

@foreach ($errors->all() as $error)
{{ $error }}
@endforeach

@endif
<!-- FORM STARTS HERE -->
<form method="POST" action
...









10
16
pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
Just like that we know can show off our
errors. This may not always be ideal though.
Sometimes our user will expect the error to
be placed next to the input it corresponds
to.
Hand-Picking Error
Messages





pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
We have the ability to do this in Laravel and
we can pick out single errors using:
// select the first error that corresponds to the name field
{{ $errors->first('name') }}
We can add this to each of our inputs and
also we will use and if statement to add a
Bootstrap error class ( has-error ) so that
Bootstrap will turn our inputs red.
<!-- app/views/duck-form.blade.php -->
...
<!-- FORM STARTS HERE -->
<form method="POST" action="/ducks" novalidate
<div class="form-group @if ($errors-
<label for="name">Name
<input type="text" id
@if ($errors->has('name'))
</div>
6
9
pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
<div class="form-group @if ($errors-
<label for="email">Email
<input type="text" id
@if ($errors->has('email'))
</div>
<div class="form-group @if ($errors-
<label for="password"
<input type="password
@if ($errors->has('password'))
</div>
<div class="form-group @if ($errors-
<label for="password_confirm
<input type="password
@if ($errors->has('password_confirm'))
</div>
<button type="submit" class="
</form>
...








12
15
18
21
24
27
pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
Now we are using if statements that will
show errors if Laravel has shown there is an
error for that field.
Each input will have the correct errors next
to it now.
pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
Now that our errors are good to go, our
user will find those messages helpful. One
other thing that they would appreciate also
is that they would probably want to have
the inputs they provided to still populate
the form. We wouldnt want our users to
enter their name and email all over again
just because their two password fields
didnt match up.
We have to add something to our form
validation on the backend side of things and
then well add the information to our view
file.
// app/routes.php
Showing Old Inputs
In the View

pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
// app/routes.php
...
// check if the validator failed -----------------------
if ($validator->fails()) {
// redirect our user back with error messages
$messages = $validator->messages();
// also redirect them back with old inputs so they dont have to fill out the form again
// but we wont redirect them with the password they entered
return Redirect::to('ducks')
->withErrors($validator)
->withInput(Input::except('password', 'password_confirm'));
} else {
...
We are redirecting users back to the form
with all inputs except the password and
password_confirm fields. This way they wont
have to enter their name and email again.
Now, we have to populate our form with the
data that comes back. Well use our input
fields value attribute and the way we get
pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
old input data from Laravel is to use:
{{ Input::old('name') }}
Well add that to our form now.
<!-- app/views/duck-form.blade.php -->
...
<!-- FORM STARTS HERE -->
<form method="POST" action="/ducks" novalidate
<div class="form-group @if ($errors-
<label for="name">Name
<input type="text" id
@if ($errors->has('name'))
</div>
<div class="form-group @if ($errors-
<label for="email">Email
<input type="text" id
@if ($errors->has('email'))
</div>
...

8
13
pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
Just like that, we are now populating our
form with data that the user submitted. Our
users will thank us for not having to enter in
information again, especially on larger
forms!

pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
The last thing well handle in form validation
for Laravel today is to create custom error
messages. Sometimes the default ones just
arent fun enough for our flare and pizazz.
All we have to do for this is to create our
custom messages and pass it into the
$validator in our routes.php file. Lets
change the messages for our required and
same fields.
Custom Error
Messages

// app/routes.php
// route to process the ducks form
Route::post('ducks', function()
pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
{
// create the validation rules ------------------------
$rules = array(
'name' =>
'email' =>
'password' =>
'password_confirm' =>
);
// create custom validation messages ------------------
$messages = array(
'required' => 'The :attribute is really really really important.'
'same' => 'The :others must match.'
);
// do the validation ----------------------------------
// validate against the inputs from our form
$validator = Validator::make(
// check if the validator failed -----------------------
if ($validator->fails()) {











15
19
23
pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
By just adding that, Laravel will
automatically send back those error
messages to the view. We dont have to
change anything on the view side of our
code.
You can create your own messages by using
the :attribute and :other fillers to fill that
space with the field name.
pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
Another way to set rules for attributes is to
do it in your models. This is a great way to
do this since all the rules are attached to
the model. This way, no matter where you
have to validate, you can always reference
back to the model. Lets look at how we can
do this.
In your model, lets create the same rules
we created ealier:
<?php
// app/models/Duck.php
Model Level Rules
pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
class Duck extends Eloquent {
protected $fillable = array('name', 'email', 'password');
public static $rules = array(
'name' => 'required', // just a normal required validation
'email' => 'required|email|unique:ducks', // required and must be unique in the ducks table
'password' => 'required',
'password_confirm' => 'required|same:password' // required and has to match the password field
);
}
Thats all we have to do in the model. Now
to access those rules when we validate, we
just pass in those rules using
ModelName::$rules .
$validator = Validator::make(Input::all(), ModelName::$rules);
You can also use this method to set rules
based on user levels, like for an admin vs a
normal user with differently named rule
pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
normal user with differently named rule
sets. So you would be able to create
$adminRules and $userRules and access
them directly.
Thanks to longshot for pointing out this
great Jeffrey Way tip.
Hopefully this was a good example of the
flexibility and features that Laravel provides
when validating forms. There is still much
more to dive into like creating custom
validation rules and conditionally adding
rules.
Conclusion
pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
I would definitely suggest checking out the
official docs for more information about the
great things you can do. Let us know if you
have any questions or comments on any
validation tactics and thanks for reading.
pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
Related Articles
View Code
7
f
Share
21
V
Tweet
11
_
Plus
AngularJS Form
Validation
Create a Laravel and
Angular Single Page
Comment
Laravel Form Model
Binding
pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
Application
A Guide to Using
Eloquent ORM in
Laravel
Building Dynamic
Angular Forms with
ngRepeat and
ngForm
Getting Started with
Laravel Homestead
Chris Sevilleja
Design, development, and
anything in between that I
find interesting.
V
pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
Stay Connected With Us
hover these for magic

Get valuable tips, articles, and resources straight to your


inbox. Every Tuesday.
View My Articles
Your Secret Electronic Address
Subscribe
Follow
1.9k
Like
1.6k
Follow
m
SUBSCRIBE
V
FOLLOW
f
LIKE
_
+1
pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
Comments Community
Sort by Best
Join the discussion
Reply
Guest 5 days ago
What i don't understand: Why do you put the validator rules inside the Duck model?
I thought this model is only responsible for the db table "ducks"?

1
Reply
Merlin a day ago
What i don't understand: Why do you put the validator rules inside the Duck model?
I thought this model is only responsible for the db table "ducks"?


Reply
Merlin 6 days ago
$duck = new Duck; .... $duck->save(); ............ is $duck automatically used a table name there? Because i can't find
any $table="duck"; or something in your code.


Share
Share
Share
pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
Reply
Chris Sevilleja 6 days ago Bartender Merlin
When you create a new Duck, you are creating a new Eloquent model for Duck. When defining your model
(Duck in this case), Eloquent knows to look at the plural version in the database. So it will look for a
table.
You can specifically name your table using
convention.

1
Reply
Guest 5 days ago Chris Sevilleja
But if you need to change the db table name then you must change the Model class name annd all
$duck-> in your scripts, right? I didn't like this a bit :)


Reply
Chris Sevilleja Bartender Guest
You don't have to do it that way. You could just specify the table name by using
'ducks';.
That would then cascade down to all the instances you pull in the Duck model.


Reply
Pete Houston 12 days ago
Just a comment, in [Model Level Rules] section, the access level for "$rules" should be "public", if you access it
outside of "Duck" class.


Chris Sevilleja 11 days ago Bartender Pete Houston
Fixed. Thanks.
Share
Share
Share
Share
pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
Reply
Reply
Matt 25 days ago
This is an awesome article. As someone looking to get deeper into Laravel, youve made it a lot easier!
Cheers!
Matt
lilly.io


Reply
Spazecookie a month ago
Really great introduction! Btw: I Guess there's a little Typo :) you probably wanted the $rules property on the model to
be public.


Reply
Chris Sevilleja 11 days ago Bartender Spazecookie
Changed to public. Thanks!


Reply
Jason Lee a month ago
Great tutorial for folks like me who are just learner Laravel.
the conclusion) was a step at the end where you move the form processing into a controller.


Chris Sevilleja a month ago Bartender Jason Lee
I actually debated doing that, but for simplicities sake, kept it in the routes. To move it into a controller (let's
say DuckController with a method called createDuck), you would move all that code into that method. Then in
Share
Share
Share
Share
Share
pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
Reply
the routes, use
Route::post('ducks', array('uses' =>

2
Reply
Merlin 6 days ago Chris Sevilleja
Why "uses"? What about: Route::post('ducks', 'DuckController@createDuck');

1
Reply
Chris Sevilleja Bartender Merlin
I believe both ways are valid. I've just gotten into the habit of doing that way.


Subscribe
Add Disqus to your site
Share
Share
Share
pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API
About Advertise Shop (coming soon) Books (coming soon)
Plugins (coming soon)
Copyright 2013-2014 Scotch.io, LLC. All Rights Reserved.
pdfcrowd.com open in browser PRO version Are you a developer? Try out the HTML to PDF API

Anda mungkin juga menyukai