Creating and validating a user using Ajax in laravel

When a user comes to our application, we may want them to register or login without the need
to navigate to another page. Using Ajax within Laravel, we can submit the user’s form and run
the validation asynchronously.

Getting ready

For this recipe, we’ll need a working installation of Laravel as well as a properly configured
MySQL database. We also need to add a user table to our database, which we can do with
the following code:
id int(10) unsigned NOT NULL AUTO_INCREMENT,
email varchar(255) DEFAULT NULL,
password char(60) DEFAULT NULL,

How to do it…

To complete this recipe, follow the given steps:
1. In the controllers directory, create a UsersController.php file:
class UsersController extends BaseController {
public function getIndex()
return View::make(‘users.index’);
public function postRegister()
$rules = array(
’email’ => ‘required|email’,
‘password’ => ‘required|min:6’
$validation = Validator::make(Input::all(), $rules);
if ($validation->fails())

return Response::json($validation->errors()->toArray());
’email’ => Input::get(’email’),
‘password’ => Hash::make(Input::get(‘password’))
return Response::json(array(‘Registration is complete!’));

2. Register the controller in routes.php:
Route::controller(‘users’, ‘UsersController’);
3. In the views directory, create a folder named users, and in that folder, create a file
named index.php:
<!doctype html>
<html lang=”en”>
<meta charset=”utf-8″>
<title>User Register</title>
<script type=”text/javascript”
<form id=”register”>
<label for=”email”>Your email:</label>
<input type=”email” name=”email” id=”email”><br>
<label for=”password”>Your password:</label>
<input type=”password” name=”password” id=”password”><br>
<input type=”submit”>
<div id=”results”></div>
$(“#register”).on(“submit”, function(e) {
var results = ”;
{email: $(“#email”).val(), password:
$(“#password”).val()}, function(data) {

$.each(data, function(){
results += this + ‘<br>’;

How it works…

To begin this recipe, we create our main page which will hold our user registration form. When
the form is submitted, it will post to our postRegister() method and return any results to
the results div.
The postRegister() method begins by setting up the rules for our validation. In this case,
we want to make sure both fields have a value, the e-mail must be valid, and the password
must be at least 6 characters. If the validation fails, we send the error back as a JSON-encoded
string and our main page will display the error. If everything is valid, we then save everything to
the database and return a success message.

Leave a Reply

Your email address will not be published. Required fields are marked *