Setting up a controller to return JSON data
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:
In the
controllers
directory, create a file namedBooksController.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); } }
In
routes.php
, register the books controllerRoute::controller('books', 'BooksController');
In the
views
directory, create a folder namedbooks
, and in that folder, create a file namedindex.php
:<!DOCTYPE html> <html> <head> <meta charset=utf-8...