How to validate a contact form created using Blade template in laravel

arjitaarjita bhubaneshar
edited September 2014 in PHP
Open app/routes.php file-
Add these codes:

Route::post('contact', function()
$data = Input::all();
$rules = array(
'subject' => 'required',
'message' => 'required'
$validator = Validator::make($data, $rules);
if($validator->fails()) {
return Redirect::to('contact')->withErrors($validator)->withInput();
return 'Your message has been sent successfully';

You can create your contact.blade.php inside ‘app/views’ directory.

Add these codes in  contact.blade.php 

<h1>Contact Us.</h1>
<p>Please contact us by sending a message using the form below:</p>
{{ HTML::ul($errors->all(), array('class'=>'errors'))}}
{{ Form::open(array('url' => 'contact')) }}
{{ Form::label('Subject') }}
{{ Form::text('subject','Enter your subject') }}
<br />
{{ Form::label('Message') }}
{{ Form::textarea('message','Enter your message') }}
<br />
{{ Form::submit() }}
{{ Form::close() }}

This tells Blade which layout we will be using to render our content. In this situation I am referring to
the ‘layout.blade.php’ file within ‘app/views’ directory.

The content of ‘layout.blade.php’  is-

<html lang="en">
<meta charset="UTF-8">
<title>Learning Laravel</title>
<li><a href="./contact">Contact</a></li>

We use @yield(‘content’) to tell Blade to create a section here, we can fill in content later. Like what we have done in contact.blade.php.

Finally you need to update your routes.php file inside app directory.

Route::get('/contact', function()
return View::make('contact');

If you’re doing correctly, when you click submit button, you will get a successful message:
 'Your message has been sent successfully'

If you want to check validation then try to remove subject field’s content and message field’s content, make them blank. You
would see the errors.

Thanks. :-)
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!