Building a shopping cart in laravel

E-commerce is a huge business on the web. An integral part of most e-commerce sites is the
use of a shopping cart system. This recipe will walk through how to use Laravel sessions to
store items for sales and build a shopping cart.

Getting ready

For this recipe, we need a standard installation of Laravel, as well as a properly set up and
configured MySQL database.

How to do it…

To complete this recipe, follow these given steps:
1. In our database, create a table and add some data with this SQL code:
CREATE TABLE items (
id int(10) unsigned NOT NULL AUTO_INCREMENT,
name varchar(255) DEFAULT NULL,
description text,
price int(11) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB;
INSERT INTO items VALUES (‘1’, ‘Lamp’, ‘This is a Lamp.’,’14’);
INSERT INTO items VALUES (‘2’, ‘Desk’, ‘This is a Desk.’,’75’);
INSERT INTO items VALUES (‘3’, ‘Chair’, ‘This is a
Chair.’, ’22’);
INSERT INTO items VALUES (‘4’, ‘Sofa’, ‘This is a
Sofa/Couch.’, ‘144’);
INSERT INTO items VALUES (‘5’, ‘TV’, ‘This is a
Television.’, ’89’);

2. In the routes.php file, create the routes for our cart with the following code:
Route::get(‘items’, function()
{
$items = DB::table(‘items’)->get();
return View::make(‘items’)->with(‘items’, $items)
>nest(‘cart’, ‘cart’, array(‘cart_items’ =>
Session::get(‘cart’)));
});
Route::get(‘item-detail/{id}’, function($id)
{
$item = DB::table(‘items’)->find($id);
return View::make(‘item-detail’)->with(‘item’, $item)
>nest(‘cart’, ‘cart’, array(‘cart_items’ =>
Session::get(‘cart’)));
});
Route::get(‘add-item/{id}’, function($id)
{
$item = DB::table(‘items’)->find($id);
$cart = Session::get(‘cart’);
$cart[uniqid()] = array (‘id’ => $item->id, ‘name’ =>
$item >name, ‘price’ => $item->price);
Session::put(‘cart’, $cart);
return Redirect::to(‘items’);
});
Route::get(‘remove-item/{key}’, function($key)
{
$cart = Session::get(‘cart’);
unset($cart[$key]);
Session::put(‘cart’, $cart);
return Redirect::to(‘items’);
});
Route::get(’empty-cart’, function()
{
Session::forget(‘cart’);
return Redirect::to(‘items’);
});
3. In the views directory, create a file named items.php with the following code:
<!doctype html>
<html lang=”en”>
<head>
<meta charset=”utf-8″>
<title>Item List</title>

</head>
<body>
<div>
<?php foreach ($items as $item): ?>
<p>
<a href=”item-detail/<?= $item->id ?>”>
<?= $item->name ?>
</a> —
<a href=”add-item/<?= $item->id ?>”>Add to Cart</a>
</p>
<?php endforeach; ?>
</div>
<?php $cart_session = Session::get(‘cart’) ?>
<?php if ($cart_session): ?>
<?= $cart ?>
<?php endif; ?>
</body>
</html>
4. In the views directory, create a file named item-detail.php by the given code:
<!doctype html>
<html lang=”en”>
<head>
<meta charset=”utf-8″>
<title>Item: <?= $item->name ?></title>
</head>
<body>
<div>
<h2><?= $item->name ?></h2>
<p>Price: <?= $item->price ?></p>
<p>Description: <?= $item->description ?></p>
<p>
<a href=”../add-item/<?= $item->id ?>”>Add to Cart</a>

</p>
<p><a href=”../items”>Item list</a></p>
</div>
<? if (Session::has(‘cart’)): ?>
<?= $cart ?>
<? endif; ?>
</body>
</html>
5. In the views directory, create a file named cart.php with the following code:
<div class=”cart” style=”border: 1px solid #555″>
<?php if ($cart_items): ?>
<?php $price = 0 ?>
<ul>

<?php foreach ($cart_items as $cart_item_key =>
$cart_item_value): ?>
<?php $price += $cart_item_value[‘price’]?>
<li>
<?= $cart_item_value[‘name’] ?>:
<?= $cart_item_value[‘price’] ?> (<a href=”remove-item/<?=
$cart_item_key ?>”>remove</a>)
</li>
<?php endforeach; ?>
</ul>
<p><strong>Total: </strong> <?= $price ?></p>
<?php endif; ?>
</div>
6. Now, we can go in our browser to http://{your-server}/items to view the list
of items from our database, links to their detail pages, and an option to add them to
a cart. When added to the cart, they will show at the bottom of the page.

How it works…

To begin this recipe, we need to set up a database table that will hold items that we want to
add to the cart. We’ll also add in a few test items, so we have some data to work with.
In our first route, we get all of the existing items in our table and display them. We’re also
nesting in a cart view that will show the items we already added. In that nested view, we also
send in our cart session, so the list can populate.
Our next route does something similar but it accepts only one item and displays the full
information.
The next route actually adds the items. First, we get the item from the database based on its
ID. Then we save the existing cart session to a variable, so we can manipulate it. We add the
item to the array, using php’s uniqid() function as our key. Then we put the cart array back
into the Session and redirect it.
If we want to remove an item, we first make a way to get the item’s ID and remove it from the
cart array. The other way is to just delete all the session and start over.
In our view, we’ll also notice that we are only allowing the cart list to show if there actually is
anything in the cart.

Using advanced validation laravel in forms

There might be times when we need to validate our forms for something that’s not part of the
framework. This recipe will show you how to build a custom validation rule and apply it.

Getting ready

For this recipe, we need a standard installation of Laravel.

How to do it…

The following are the steps to complete this recipe:
1. In the views directory, create a file named valid.php to hold our form using the
following code:
<!doctype html>
<html lang=”en”>
<head>
<meta charset=”utf-8″>
<title>Custom Validation</title>
</head>
<body>
<p>
<?php if ($errors): ?>
<?php echo $errors->first(’email’) ?>
<?php echo $errors->first(‘captain’) ?>
<?php endif; ?>
</p>
<p>
<h3>Custom Validation</h3>
<?= Form::open(array(‘url’ => ‘valid’, ‘method’ => ‘post’))
?>
<?= Form::label(’email’, ‘Email’) ?>
<?= Form::text(’email’) ?><br><br>
<?= Form::label(‘captain’, ‘Your favorite captains (choose
three)’) ?><br>
<?= ‘Pike: ‘ . Form::checkbox(‘captain[]’, ‘Pike’) ?><br>
<?= ‘Kirk: ‘ . Form::checkbox(‘captain[]’, ‘Kirk’) ?><br>

<?= ‘Picard: ‘ . Form::checkbox(‘captain[]’, ‘Picard’)
?><br>
<?= ‘Sisko: ‘ . Form::checkbox(‘captain[]’, ‘Sisko’) ?><br>
<?= ‘Janeway: ‘ . Form::checkbox(‘captain[]’, ‘Janeway’)
?><br>
<?= ‘Archer: ‘ . Form::checkbox(‘captain[]’, ‘Archer’)
?><br>
<?= ‘Crunch: ‘ . Form::checkbox(‘captain[]’, ‘Crunch’)
?><br>
<?= Form::submit(‘Submit’) ?>
<?= Form::close() ?>
</p>
</body>
</html>

2. In the routes.php file, create our routes with the following code:
Route::get(‘valid’, function()
{
return View::make(‘valid’);
});
Route::post(‘valid’, function()
{
$rules = array(’email’ => ‘required|email’,
‘captain’ => ‘required|check_three’);
$messages = array(
‘check_three’ => ‘Thou shalt choose three captains. No
more. No less. Three shalt be the number thou shalt
choose, and the number of the choosing shall be
three.’,);
$validation = Validator::make(Input::all(), $rules,
$messages);
if ($validation->fails())
{
return Redirect::to(‘valid’)->withErrors($validation);
}
echo “Form is valid!”;
});
3. Also in the routes.php file, create our custom validation as given in the
following code:
Validator::extend(‘check_three’, function($attribute,
$value, $parameters)
{
return count($value) == 3;
});

How it works…

To begin, we create the form in our view. We ask for a valid e-mail and exactly three of the
checkboxes to be checked. Since there’s no Laravel validation method for exactly three
checkboxes, we need to create a custom validation.
Our custom validation takes the input array and does a simple count. If it comes up to three, it
returns TRUE. If not, it returns FALSE and fails the validation.
Back in our form processing route, all we then need to do is add the name of the custom
validator we created to our validation rules. If we want to set a custom message, we can add
that as well.

Creating a sortable table using jQuery and Laravel

When handling large amounts of data, it can be helpful to display it in a table view. To manipulate
the data, such as for sorting or searching, we can use the data tables JavaScript library. This way,
we don’t need to keep making database calls every time we want to change the view.

Getting ready

For this recipe, we need a standard installation of Laravel and a properly configured
MySQL database.

How to do it…

Follow the given steps to complete this recipe:
1. In our database, create a new table and add some example data using the
following commands:
DROP TABLE IF EXISTS bookprices;
CREATE TABLE bookprices (
id int(10) unsigned NOT NULL AUTO_INCREMENT,
price float(10,2) DEFAULT NULL,
book varchar(100) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO bookprices VALUES (‘1’, ‘14.99’, ‘Alice in
Wonderland’);
INSERT INTO bookprices VALUES (‘2’, ‘24.50’,
‘Frankenstein’);
INSERT INTO bookprices VALUES (‘3’, ‘29.80’, ‘War and
Peace’);
INSERT INTO bookprices VALUES (‘4’, ‘11.08’, ‘Moby
Dick’);
INSERT INTO bookprices VALUES (‘5’, ‘19.72’, ‘The Wizard
of Oz’);
INSERT INTO bookprices VALUES (‘6’, ‘45.00’, ‘The
Odyssey’);
2. In the app/models directory, create a file named Bookprices.php with the
following code snippet:
<?php
class Bookprices extends Eloquent {
}
3. In the routes.php file, add our route as given in the following code:
Route::get(‘table’, function()
{
$bookprices = Bookprices::all();
return View::make(‘table’)->with(‘bookprices’,
$bookprices);
});
4. In the views directory, create a file named table.php with the following code:
<!doctype html>
<html lang=”en”>
<head>
<meta charset=”utf-8″>
<title></title>
<script src=”//ajax.googleapis.com/ajax/libs/jquery
/1.10.2/jquery.min.js”></script>
<script src=”//ajax.aspnetcdn.com/ajax/jquery.dataTables
/1.9.4/jquery.dataTables.min.js”></script>
<link rel=”stylesheet” type=”text/css” href=”
//ajax.aspnetcdn.com/ajax/jquery.dataTables/
1.9.4/css/jquery.dataTables.css”>
</head>

<body>
<h1>Book List</h1>
<table>
<thead>
<tr>

<th>Price</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<?php foreach ($bookprices as $book): ?>
<tr>
<td><?php echo $book[‘price’] ?></td>
<td><?php echo $book[‘book’] ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<script>
$(function(){
$(“table”).dataTable();
});
</script>
</body>
</html>

How it works…

To start this recipe, we create a table to hold our book price data. We then insert the data into
the table. Next, we create an Eloquent model so we can interact with the data. We then pass
that data into our view.
In our view, we load in jQuery and the dataTables plugin. Then, we create a table to hold
our data and then loop through the data, putting each record into a new row. When we add
the dataTable plugin to our table, it will automatically add sorting to our table for each of
our columns.

Sending an e-mail using Laravel and jQuery in laravel

When creating a contact form, we may choose to let the user send the form asynchronously.
Using Laravel and jQuery, we can have the form submitted without needing the user to go to a
different page.

Getting ready

For this recipe, we need a standard Laravel installation and our mail client properly
configured. We can update our mail configuration in the app/config/mail.php file.

How to do it…

To complete this recipe, follow the given steps:
1. In the views directory, create a file named emailform.php as shown in the
following code:
<!doctype html>
<html lang=”en”>
<head>
<meta charset=”utf-8″>
<title></title>
<script src=”//ajax.googleapis.com/ajax/libs
/jquery/1.10.2/jquery.min.js”></script>
</head>
<body>
<div id=”container”>
<div id=”error”></div>
<form id=”email-form”>
<label>To: </label>
<input name=”to” type=”email”><br>
<label>From: </label>
<input name=”from” type=”email”><br>
<label>Subject: </label>
<input name=”subject”><br>
<label>Message:</label><br>
<textarea name=”message”></textarea><br>
<input type=”submit” value=”Send”>
</form>
</div>
<script>
$(function(){
$(“#email-form”).on(‘submit’, function(e){
e.preventDefault();
$.post(’email-send’, $(this).serialize(), function(data){
if (data == 0) {
$(“#error”).html(‘<h3>There was an error</h3>’);

} else {
if (isNaN(data)) {
$(“#error”).html(‘<h3>’ + data + ‘</h3>’);
} else {
$(“#container”).html(‘Your email has been sent!’);
}
}
});
});
});
</script>
</body>
</html>

2. In the views folder, create our e-mail template view file named ajaxemail.php
with the following code:
<!DOCTYPE html>
<html lang=”en-US”>
<head>
<meta charset=”utf-8″>
</head>
<body>
<h2>Your Message:</h2>
<div><?= $message ?></div>
</body>
</html>
3. In the routes.php file, create the routes as given in the following code snippet:
Route::get(’email-form’, function()
{
return View::make(’emailform’);
});
Route::post(’email-send’, function()
{
$input = Input::all();
$rules = array(
‘to’ => ‘required|email’,
‘from’ => ‘required|email’,
‘subject’ => ‘required’,
‘message’ => ‘required’
);
$validation = Validator::make($input, $rules);
if ($validation->fails())

{
$return = ”;
foreach ($validation->errors()->all() as $err) {
$return .= $err . ‘<br>’;
}
return $return;
}
$send = Mail::send(‘ajaxemail’, array(‘message’ =>
Input::get(‘message’)), function($message)
{
$message->to(Input::get(‘to’))
->replyTo(Input::get(‘from’))
->subject(Input::get(‘subject’));
});
return $send;
});

How it works…

For this recipe, we need to have our e-mail client properly configured. We have many options
to choose from, including PHP’s mail() method, sendmail, and SMTP. We could even use a
third-party e-mail service such as mailgun or postmark.
Our e-mail form is a regular HTML form with four fields: the to and from e-mail addresses,
the subject line, and the actual e-mail message. When the form is submitted, the fields are
serialized and posted to our email-send route.
The email-send route first validates all of the posted input. If there are any validation
errors, they are returned back as a string. If everything checks out, we send our values to the
Mail::send method and then send it.
Back in our e-mail-form route JavaScript, we check if email-send returned FALSE, and
if so, we display an error. If not, we need to check if the response was a number or not. If
it wasn’t a number, that means there were validation errors and we display them. If it is a
number, that means the e-mail was sent successfully, so we display a success message.

Making an Ajax newsletter sign-up box in laravel

One way to have users added to our e-mail list is to have them sign-up through our website.
In this recipe, we’ll be using MailChimp’s API and a modal window to show a sign-up form and
have it sent through an Ajax call.

Getting ready

For this recipe, we’ll need a standard Laravel installation. We’ll also be using the MailChimp API
for the newsletter; a free account and API key can be created at www.mailchimp.com.

How to do it…

To complete this recipe, follow the given steps:
1. Open the composer.json file and update the require section to resemble the
following code:
“require”: {
“laravel/framework”: “4.0.*”,
“rezzza/mailchimp”: “dev-master”
}
2. In the command-line window, where the artisan file is located, update Composer with
the following command:
php composer.phar update

3. In the app/config directory, create a file named mailchimp.php:
<?php
return array(
‘key’ => ‘12345abcde-us1’,
‘list’ => ‘123456789’
);
4. In the views directory, create a file named signup.php:
<!doctype html>
<html lang=”en”>
<head>
<meta charset=”utf-8″>
<title>Newsletter Signup</title>
<link href=”//netdna.bootstrapcdn.com/twitterbootstrap/
2.2.2/css/bootstrap-combined.min.css”
rel=”stylesheet”>
<script src=”//ajax.googleapis.com/ajax/libs/jquery/
1.9.0/jquery.min.js”></script>
<script src=”//netdna.bootstrapcdn.com/twitterbootstrap/
2.2.2/js/bootstrap.min.js”></script>
</head>
<body>
<p>
<a href=”#signupModal” role=”button” class=”btn btn-info”
data-toggle=”modal”>Newsletter Signup</a>
</p>
<div id=”results”></div>
<div id=”signupModal” class=”modal hide fade”>
<div class=”modal-header”>
<button type=”button” class=”close” data-dismiss=”modal”
aria-hidden=”true”>&times;</button>
<h3>Sign-up for our awesome newsletter!</h3>

</div>
<div class=”modal-body”>
<p>
<form id=”newsletter_form”>
<label>Your First Name</label>
<input name=”fname”><br>
<label>Last Name</label>
<input name=”lname”><br>
<label>Email</label>
<input name=”email”>
</form>
</p>
</div>
<div class=”modal-footer”>

<a href=”#” class=”btn close” datadismiss=”
modal”>Close</a>
<a href=”#” class=”btn btn-primary”
id=”newsletter_submit”>Signup</a>
</div>
</div>
<script>
$(function(){
$(“#newsletter_submit”).on(‘click’, function(e){
e.preventDefault();
$(“#results”).html(“loading…”);
$.post(‘signup-submit’,
$(“#newsletter_form”).serialize(),
function(data){
$(‘#signupModal’).modal(‘hide’);
$(“#results”).html(data);
});
});
});
</script>
</body>
</html>

5. In the routes.php file, add the routes we need with the following code:
Route::get(‘signup’, function()
{
return View::make(‘signup’);
});
Route::post(‘signup-submit’, function()
{
$mc = new MCAPI(Config::get(‘mailchimp.key’));
$response = $mc->listSubscribe(
‘{list_id}’,
Input::get(’email’),
array(
‘FNAME’ => Input::get(‘fname’),
‘LNAME’ => Input::get(‘lname’)
)
);
if ($mc->errorCode){
return ‘There was an error: ‘ . $mc->errorMessage;
} else {
return ‘You have been subscribed!’;
}
});

How it works…

We start by installing the MailChimp package into our application using a composer version of
the MailChimp SDK. We then need to create a configuration file to hold our API key and the list
ID we want to use.
Our sign-up page will utilize jQuery and Bootstrap for our processing and display. Since we
only want to display the form when the user wants to sign-up, we have a single button that,
when clicked on, will display a modal window with our form. The form will take out first name,
last name, and e-mail address.
When the sign-up form is submitted, we serialize the data and send it to our signup-submit
route. Once we get a response, we hide the modal and display the results on our page.
In our signup-submit route, we attempt to subscribe the user with the information entered.
If we get a response, we check if the response includes an error. If there is an error, we display
that to the user, and if not, we show our success message.

 

Filtering data based on checkbox selection in laravel

When displaying data to a user, it could be convenient to allow them to filter the data. So we
don’t have to make the user click on submit and reload the page every time, we can do all the
filtering using Ajax. For this recipe, we’ll make a book list and allow the user to filter it based
on the genre.

Getting ready

For this recipe, we need a standard Laravel installation that’s configured to work with a
database. We’ll need to set up a table to use by running this SQL statement:
DROP TABLE IF EXISTS books;
CREATE TABLE books (
id int(10) unsigned NOT NULL AUTO_INCREMENT,
name varchar(255) DEFAULT NULL,
author varchar(255) DEFAULT NULL,
genre varchar(255) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO books VALUES (‘1’, ‘Alice in Wonderland’,
‘Lewis Carroll’, ‘fantasy’);
INSERT INTO books VALUES (‘2’, ‘Tom Sawyer’, ‘Mark
Twain’, ‘comedy’);
INSERT INTO books VALUES (‘3’, ‘Gulliver\’s Travels’,
‘Jonathan Swift’, ‘fantasy’);

INSERT INTO books VALUES (‘4’, ‘The Art of War’, ‘Sunzi’,
‘philosophy’);
INSERT INTO books VALUES (‘5’, ‘Dracula’, ‘Bram Stoker’,
‘horror’);
INSERT INTO books VALUES (‘6’, ‘War and Peace’, ‘Leo
Tolstoy’, ‘drama’);
INSERT INTO books VALUES (‘7’, ‘Frankenstein’, ‘Mary
Shelley’, ‘horror’);
INSERT INTO books VALUES (‘8’, ‘The Importance of Being
Earnest’, ‘Oscar Wilde’, ‘comedy’);
INSERT INTO books VALUES (‘9’, ‘Peter Pan’, ‘J. M.
Barrie’, ‘fantasy’);

How to do it…

To complete this recipe, follow these steps:
1. In the controllers directory, create a new file named BooksController.php:
<?php
class BooksController extends BaseController {
public function getIndex()
{
return View::make(‘books.index’);
}

public function postBooks()
{
if (!$genre = Input::get(‘genre’)) {
$books = Book::all();
} else {
$books = Book::whereIn(‘genre’, $genre)->get();
}
return $books;
}
}
2. Register the books controller in the routes.php file:
Route::controller(‘books’, ‘BooksController’);
3. In the views directory, create a new folder named books, and in that folder, create a
file named index.php:
<!doctype html>
<html lang=”en”>
<head>
<meta charset=”utf-8″>

<title>Books filter</title>
<scriptsrc=”//ajax.googleapis.com/ajax/libs/jquery
/1.10.2/jquery.min.js”></script>
</head>
<body>
<form id=”filter”>
Comedy: <input type=”checkbox” name=”genre[]”
value=”comedy”><br>
Drama: <input type=”checkbox” name=”genre[]”
value=”drama”><br>
Fantasy: <input type=”checkbox” name=”genre[]”
value=”fantasy”><br>
Horror: <input type=”checkbox” name=”genre[]”
value=”horror”><br>
Philosophy: <input type=”checkbox” name=”genre[]”
value=”philosophy”><br>
</form>
<hr>
<h3>Results</h3>
<div id=”books”></div>
<script>
$(function(){
$(“input[type=checkbox]”).on(‘click’, function() {
var books = ”;
$(“#books”).html(‘loading…’);
$.post(‘books/books’, $(“#filter”).serialize(),
function(data){
$.each(data, function(){
books += this.name + ‘ by ‘ + this.author + ‘ (‘ +
this.genre + ‘)<br>’;
});
$(“#books”).html(books);
});
});
});
</script>
</body>
</html>
4. In the models directory, create a file named Book.php:
<?php
class Book extends Eloquent {
}
5. In the browser, go to http://{my-server}/books and click on a few checkboxes
to see the result.

How it works…

With our database set up, we begin with our main list page. This page has a number of
checkboxes, with the value of each corresponding to a genre in our books table. When a box
is checked, the form is submitted asynchronously to our postBooks() method. We use those
results, loop through them, and display them in our books div.
Our postBooks() method begins by making sure a genre was actually submitted. If not, that
means everything is unchecked and it will return all the books. If something is checked, we
get everything from the database that matches the checked values. Since Laravel provides us
with the raw returned data in JSON format, we then return the results, and in our index, the
results are displayed correctly.

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:
CREATE TABLE users (
id int(10) unsigned NOT NULL AUTO_INCREMENT,
email varchar(255) DEFAULT NULL,
password char(60) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

How to do it…

To complete this recipe, follow the given steps:
1. In the controllers directory, create a UsersController.php file:
<?php
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());
}
else
{
DB::table(‘users’)->insert(array(
’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”>
<head>
<meta charset=”utf-8″>
<title>User Register</title>
<script type=”text/javascript”
src=”http://ajax.googleapis.com/ajax/libs/jquery/
1.9.0/jquery.min.js”></script>
</head>
<body>
<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”>
</form>
<div id=”results”></div>
<script>
$(function(){
$(“#register”).on(“submit”, function(e) {
e.preventDefault();
var results = ”;
$.post(‘users/register’,
{email: $(“#email”).val(), password:
$(“#password”).val()}, function(data) {

$.each(data, function(){
results += this + ‘<br>’;
});
$(“#results”).html(results);
});
});
});
</script>
</body>
</html>

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.

Creating an Ajax search function in laravel

If we want to search for information in our application, it might be useful to perform the search
asynchronously. That way, the user won’t have to be taken to a new page and have all the assets
refreshed. Using Laravel and JavaScript, we can perform this search in a very simple manner.
Getting ready
For this recipe, we’ll need a working installation of Laravel.
How to do it…
To complete this recipe, follow these steps:
1. In the controllers directory, create a file named SearchController.php:
<?php
class SearchController extends BaseController {
public function getIndex()
{
return View::make(‘search.index’);
}
public function postSearch()
{
$return = array();

$term = Input::get(‘term’);
$books = array(
array(‘name’ => ‘Alice in Wonderland’, ‘author’ => ‘Lewis
Carroll’),
array(‘name’ => ‘Tom Sawyer’, ‘author’ => ‘Mark
Twain’),
array(‘name’ => ‘Gulliver\’s Travels’, ‘author’ =>
‘Jonathan Swift’),
array(‘name’ => ‘The Art of War’, ‘author’ => ‘Sunzi’),
array(‘name’ => ‘Dracula’, ‘author’ => ‘Bram Stoker’),
array(‘name’ => ‘War and Peace’, ‘author’ =>
‘LeoTolstoy’),
);
foreach ($books as $book) {
if (stripos($book[‘name’], $term) !== FALSE) $return[] =
$book;
}
return Response::json($return);
}
}
2. In the routes.php file, register the controller:
Route::controller(‘search’, ‘SearchController’);
3. In the views directory, create a folder named search, and in that folder, create a file
named index.php:

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>AJAX Search</title>
<script type=”text/javascript”
src=”//ajax.googleapis.com/ajax/libs/jquery/
1.9.0/jquery.min.js”></script>
</head>
<body>
<h1>Search</h1>
<form id=”search-form”>
<input name=”search” id=”term”> <input type=”submit”>
</form>
<div id=”results”></div>
<script>
$(function() {
$(“#search-form”).on(“submit”, function(e) {
e.preventDefault();

var search_term = $(“#term”).val();
var display_results = $(“#results”);
display_results.html(“loading…”);
var results = ”;
$.post(“search/search”, {term: search_term}, function(data)
{
if (data.length == 0) {
results = ‘No Results’;
} else {
$.each(data, function() {
results += this.name + ‘ by ‘ + this.author + ‘<br>’;
});
}
display_results.html(results);
});
})
});
</script>
</body>
</html>

How it works…

We first create a RESTful controller that holds two methods: one for our main page and one
to process the search. On our main page, we have a single text field and a submit button.
When the form is submitted, our JavaScript will post the form to our search page. If there are
results, it will loop through them and display them in our results div.
For our postSearch() method, we use an array as our data source. When a search is
posted, we then loop through the array to see if the string matches any of our titles. If so,
the value is added to an array and that array is returned as a JSON.

Setting up a controller to return JSON data in laravel

When we access data using JavaScript, one of the easiest ways is to use JSON-formatted data.
In Laravel, we can return JSON from one of our controllers to be used by our JavaScript on
another page.

Getting ready

For this recipe, we need a standard Laravel installation.

How to do it…

For this recipe, follow the given steps:
1. In the controllers directory, create a file named BooksController.php:
<?php
class BooksController extends BaseController {
public function getIndex()
{
return View::make(‘books.index’);
}
public function getBooks()
{
$books = array(
‘Alice in Wonderland’,
‘Tom Sawyer’,
‘Gulliver\’s Travels’,

‘Dracula’,
‘Leaves of Grass’
);
return Response::json($books);
}
}

2. In routes.php, register the books controller
Route::controller(‘books’, ‘BooksController’);
3. In the views directory, create a folder named books, and in that folder, create a file
named index.php:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Show Books</title>
<script type=”text/javascript”
src=”//ajax.googleapis.com/ajax/libs/jquery/1.9.0/
jquery.min.js”></script>
</head>
<body>
<a href=”#” id=”book-button”>Load Books</a>
<div id=”book-list”></div>
<script>
$(function() {
$(‘#book-button’).on(‘click’, function(e) {
e.preventDefault();
$(‘#book-list’).html(‘loading…’);
$.get(‘books/books’, function(data) {
var book_list = ”;
$.each(data, function(){
book_list += this + ‘<br>’;
})
$(“#book-list”).html(book_list);
$(‘#book-button’).hide();
});
});
});

</script>
</body>
</html>

How it works…

We begin by creating a RESTful controller for our book list which extends our
BaseController class. Our controller has two methods: one to display the list and one to
return the formatted list. Our getBooks() method uses an array as our data source, and we
use Laravel’s Response::json() method to automatically do the correct formatting for us.
On our main page, we do a get request to the page in JavaScript, receive the JSON, and loop
through the results. As we loop, we add the books to a JavaScript variable and then add the
list to our book-list div.

 

Getting data from another page in laravel

In our application, there may be times when we need to access some HTML from another
page. Using Laravel and jQuery, we can accomplish this easily.

Getting ready

For this recipe, we just need a standard Laravel installation.

How to do it…

To complete this recipe, follow the given steps:
1. Open the routes.php file:
Route::get(‘getting-data’, function()
{
return View::make(‘getting-data’);
});
Route::get(‘tab1’, function()
{
if (Request::ajax()) {
return View::make(‘tab1’);
}
return Response::error(‘404’);
});
Route::get(‘tab2’, function()
{
if (Request::ajax()) {
return View::make(‘tab2’);
}
return Response::error(‘404’);
});
2. In the views directory, create a file named tab1.php:
<h1>CHAPTER 1 – Down the Rabbit-Hole</h1>
<p>
Alice was beginning to get very tired of sitting by her
sister on the bank,
and of having nothing to do: once or twice she had peeped
into the book her sister
was reading, but it had no pictures or conversations in
it, ‘and what is the
use of a book,’ thought Alice ‘without pictures or
conversation?’

</p>
<p>
So she was considering in her own mind (as well as she
could, for the
hot day made her feel very sleepy and stupid), whether
the pleasure of making
a daisy-chain would be worth the trouble of getting up
and picking the daisies,
when suddenly a White Rabbit with pink eyes ran close by
her.
</p>
3. In the views directory, create a file named tab2.php:
<h1>Chapter 1</h1>
<p>”TOM!”</p>
<p>No answer.</p>
<p>”TOM!”</p>
<p>No answer.</p>
<p>”What’s gone with that boy, I wonder? You TOM!”</p>
<p>No answer.</p>
<p>
The old lady pulled her spectacles down and looked over them
about the room;
then she put them up and looked out under them. She seldom
or never looked
through them for so small a thing as a boy; they were her
state pair,
the pride of her heart, and were built for “style,” not
service—she could
have seen through a pair of stove-lids just as well. She
looked perplexed
for a moment, and then said, not fiercely, but still loud
enough for the

furniture to hear:
</p>
<p>”Well, I lay if I get hold of you I’ll—”</p>
<p>
She did not finish, for by this time she was bending down
and punching
under the bed with the broom, and so she needed breath to
punctuate
the punches with. She resurrected nothing but the cat.
</p>

4. In the views directory, create a file named getting-data.php:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Getting Data</title>
<script type=”text/javascript”
src=”//ajax.googleapis.com/ajax/libs/jquery
/1.9.0/jquery.min.js”></script>
</head>
<body>
<ul>
<li><a href=”#” id=”tab1″ class=”tabs”>Alice In
Wonderland</a></li>
<li><a href=”#” id=”tab2″ class=”tabs”>Tom Sawyer</a></li>
</ul>
<h1 id=”title”></h1>
<div id=”container”></div>
<script>
$(function() {
$(“.tabs”).on(“click”, function(e) {
e.preventDefault();
var tab = $(this).attr(“id”);
var title = $(this).html();
$(“#container”).html(“loading…”);
$.get(tab, function(data) {
$(“#title”).html(title);
$(“#container”).html(data);
});
});
});
</script>
</body>
</html>
5. View the page at http://{yourserver}/getting-data and click on the links to
load the content.

How it works…

We start by setting up our routes. Our first route is going to display links, and when we click
on them, content will be loaded into the page. Our next two routes will hold the actual content
to display on the main page. To make sure that these pages can’t be accessed directly, we
use the Request::ajax() method to make sure that only Ajax requests are accepted. If
someone tries to access the page directly, it will send them to an error page.

Our two view files will hold a couple of excerpts from books. Since this will be loaded into
another page, we don’t need the full HTML. Our main page, however, is a full HTML page. We
begin by loading jQuery using the Content Delivery Network (CDN) from Google. Then, we
have a list of the books we want to use. To make things a little easier, the ID of the link will
correspond to the routes we created.
When someone clicks on the link, the script will use the ID and get the content from the route
with the same name. The results will be loaded into our container div.