Building a RESTful API with routes in laravel

A common need for a modern web application is having an API that third-parties can run
queries against. Since Laravel is built with RESTful patterns as a focus, it’s quite easy to build
a full API with very little work.

Getting ready

For this recipe, we need a standard Laravel installation with a properly configured MySQL
database tied into our application.

How to do it…

To complete this recipe, follow these steps:
1. Open the command line, go to the root directory of the Laravel installation, and create
a migration for our table using the following:
php artisan migrate:make create_shows_table
2. In the app/database/migrations directory, find the file similar to
2012_12_01_222821_create_shows_table.php and create the schema
for our table as follows:
<?php
use Illuminate\Database\Migrations\Migration;
class CreateShowsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create(‘shows’, function($table)
{
$table->increments(‘id’);
$table->string(‘name’);
$table->integer(‘year’);
$table->timestamps();
});

}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop(‘shows’);
}
}

3. Back in the command line, run the migration as follows:
php artisan migrate
4. Create another migration to add some test data:
php artisan migrate:make add_shows_data
5. In the app/database/migrations folder, open the add_shows_data file and
add the query as follows:
<?php
use Illuminate\Database\Migrations\Migration;
class AddShowsData extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
$shows = array(
array(
‘name’ => ‘Happy Days’,
‘year’ => 1981
),
array(
‘name’ => ‘Seinfeld’,
‘year’ => 1998
),
array(
‘name’ => ‘Arrested Development’,
‘year’ => 2006

)
);
DB::table(‘shows’)->insert($shows);
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
DB::table(‘shows’)->delete();
}
}

6. In the command line, run the migration as follows:
php artisan migrate
7. In the app/models directory, create a file named Show.php and add the following
code to it:
<?php
class Show extends Eloquent {
protected $table = ‘shows’;
}
8. In routes.php, create a route to return a JSON of all the shows or a single show as
follows:
Route::get(‘show/{id?}’, function($id = null)
{
if (!$id)
{
return Show::all();
}
if ($show = Show::find($id))
{
return $show;
}
});
9. Create a route that will add in new shows as follows:
Route::post(‘show’, function()
{
$show = new Show;
$show->name = Input::get(‘name’);
$show->year = Input::get(‘year’);
$show->save();

return $show;
});
10. Create a route that will delete a record:
Route::delete(‘show/{id}’, function($id)
{
if ($show = Show::find($id))
{
$show->delete();
return json_encode(array(‘message’ => ‘Record ‘ . $id
. ‘ deleted.’));
}
});

11. Create a route to update a record:
Route::put(‘show/{id}’, function($id)
{
if ($show = Show::find($id))
{
if (Input::get(‘name’)) {
$show->name = Input::get(‘name’);
}
if (Input::get(‘year’)) {
$show->year = Input::get(‘year’);
}
$show->save();
return $show;
}
});
12. Make a route to hold our add and edit show form:
Route::get(‘show-form/{id}’, function($id = null)
{
$data = array();
if ($id)
{
if (!$show = Show::find($id))
{
return ‘No show with that ID’;
}

$data = array(
‘id’ => $id,
‘method’ => ‘PUT’,
‘name’ => $show->name,
‘year’ => $show->year
);
}
else
{
$data = array(
‘id’ => ”,
‘method’ => ‘POST’,
‘name’ => ”,
‘year’ => ”
);
}
return View::make(‘show-form’, $data);
});

13. Make a route to show a list so we can delete a show:
Route::get(‘show-delete’, function()
{
$shows = Show::all();
return View::make(‘show-delete’)->with(‘shows’,
$shows);
});
14. In our app/views folder, create a file named show-form.php and add the following
code to it:
<?php echo Form::open(array(‘url’ => ‘show/’ . $id, ‘method’ =>
$method)) ?>
<?php echo Form::label(‘name’, ‘Show Name: ‘) . Form::text(‘name’,
$name) ?>
<br>
<?php echo Form::label(‘year’, ‘Show Year: ‘) . Form::text(‘year’,
$year) ?>
<br>
<?php echo Form::submit() ?>
<?php echo Form::close() ?>

15. Then, in app/views, create a file named show-delete.php and add the following
code to it:
<?php foreach ($shows as $show): ?>
<?php echo Form::open(array(‘url’ => ‘show/’ .
$show->id, ‘method’ => ‘DELETE’)) ?>
<?php echo Form::label(‘name’, ‘Show Name: ‘) .
$show->name ?>
<?php echo Form::submit(‘Delete’) ?>
<?php echo Form::close() ?>
<?php endforeach; ?>
16. Test it out by going to the show-form and show-delete routes in the browser.

How its works…

Our first step is to create our tables with the data we want to use. Using artisan and
migrations, we create a shows table and then add in some test data.
For our routes, we’re going to respond to four different HTTP verbs, GET, POST, PUT, and
DELETE, but all at the same URL, show. The GET request will serve two purposes. First, if
no ID is passed in the URL, it will display the entire list from the database. Second, if there
is an ID, it will display the single record. By returning the eloquent object directly, it will
automatically take our object and display it as JSON.

Leave a Reply

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