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:
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’,

‘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>
<meta charset=utf-8 />
<title>Show Books</title>
<script type=”text/javascript”
<a href=”#” id=”book-button”>Load Books</a>
<div id=”book-list”></div>
$(function() {
$(‘#book-button’).on(‘click’, function(e) {
$.get(‘books/books’, function(data) {
var book_list = ”;
$.each(data, function(){
book_list += this + ‘<br>’;


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.


Leave a Reply

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