scotch io tutorials php laravel form validation

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 BAR TALK TUTORIALS SERIES QUICK TIPS PROJECTS ABOUT

Upload: vercillius-avanzado-mila

Post on 20-Jul-2016

106 views

Category:

Documents


1 download

DESCRIPTION

laravel

TRANSCRIPT

pdfcrowd.comopen in browser PRO version Are you a developer? Try out the HTML to PDF API

Laravel FormValidation

Chris Sevilleja July 8, 2014 ·forms, laravel, validation 15 Comments

PHPAdvertisements

FollowFollowLike SCO TCH

BAR TALK TUTO RIALS SERIES Q UICK TIPS PRO JECTS ABO UT

pdfcrowd.comopen 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 userdoesn’t have to retype inputs

Create custom error messages

That’s a lot to do so let’s get started. We’ll

start by setting up our database.

Once we’ve got Laravel all set up, let’s go to

our command line and create our migration

so that our database table will be created.

Database andModels

pdfcrowd.comopen 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\Blueprintuse 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.comopen 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 let’s 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.comopen 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.comopen 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. We’ll 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 formRoute::get('ducks', function() { return View::make('duck-form');});

// route to process the ducks formRoute::post('ducks', function(){

// process the form here

});

Setting Up OurRoutes

pdfcrowd.comopen 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 we’ll

also be POSTing to the same URL. With our

routes ready, let’s create the duck-formthat 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 we’ll

use Laravel’s Blade to handle our views. For

Creating Our View

pdfcrowd.comopen in browser PRO version Are you a developer? Try out the HTML to PDF API

more information on Blade, here’s a starter

Blade article.

Here’s that view file. We’ll use Bootstrap to

make our views look good and then we’ll

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.comopen 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.comopen in browser PRO version Are you a developer? Try out the HTML to PDF API

Now that we have our view, we’ll be going

through all the validations needed. Since we

already have our form’s 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.

Let’s start off our validation now in that

routes.php file. We’re going to create our

rules, run the validation on the form inputs,

and handle the error messages from there.

Validating Our Form

Basic FormValidation

pdfcrowd.comopen in browser PRO version Are you a developer? Try out the HTML to PDF API

Creating Rules

Let’s create those rules:

<?php // app/routes.php

...// route to process the ducks formRoute::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.comopen 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.comopen 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 emailform

An email that has to be unique in thedatabase

A required password

A password_confirm field that needs tomatch password

So we have set the rules for our inputs. We

have run the validation and checked if that

worked. If it didn’t work, we are sending our

user back to our form with the errors.

pdfcrowd.comopen 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.

Let’s 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 Inthe View

pdfcrowd.comopen in browser PRO version Are you a developer? Try out the HTML to PDF API

Dumping Out All ErrorMessages

<!-- 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.comopen 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 ErrorMessages

pdfcrowd.comopen 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.comopen 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.comopen 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.comopen 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 wouldn’t want our users to

enter their name and email all over again

just because their two password fields

didn’t match up.

We have to add something to our form

validation on the backend side of things and

then we’ll add the information to our view

file.

// app/routes.php

Showing Old InputsIn the View

pdfcrowd.comopen 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 won’t

have to enter their name and email again.

Now, we have to populate our form with the

data that comes back. We’ll use our input

field’s value attribute and the way we get

pdfcrowd.comopen 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') }}

We’ll 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.comopen 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.comopen in browser PRO version Are you a developer? Try out the HTML to PDF API

The last thing we’ll handle in form validation

for Laravel today is to create custom error

messages. Sometimes the default ones just

aren’t 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. Let’s

change the messages for our required and

same fields.

Custom ErrorMessages

// app/routes.php

// route to process the ducks formRoute::post('ducks', function()

pdfcrowd.comopen 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.comopen 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 don’t 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.comopen 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. Let’s look at how we can

do this.

In your model, let’s create the same rules

we created ealier:

<?php// app/models/Duck.php

Model Level Rules

pdfcrowd.comopen 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 );

}

That’s 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.comopen 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.comopen 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.comopen 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

Follow1.9k

Like

1.6k

Follow

SUBSCRIBE

FOLLOW

LIKE

+1

pdfcrowd.comopen 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 findany $table="duck"; or something in your code.

Share ›

Share ›

Share ›

pdfcrowd.comopen in browser PRO version Are you a developer? Try out the HTML to PDF API

• Reply •

Chris Sevilleja • 6 days agoBartender 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 itoutside of "Duck" class.

Chris Sevilleja • 11 days agoBartender Pete Houston

Fixed. Thanks.

Share ›

Share ›

Share ›

Share ›

pdfcrowd.comopen 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!Mattlilly.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 tobe public.

• Reply •

Chris Sevilleja • 11 days agoBartender 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 agoBartender Jason Lee

I actually debated doing that, but for simplicities sake, kept it in the routes. To move it into a controller (let'ssay DuckController with a method called createDuck), you would move all that code into that method. Then in

Share ›

Share ›

Share ›

Share ›

Share ›

pdfcrowd.comopen 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.comopen 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.