This is an example for creating an API that stores bookmarks. It uses the Route::resource()
method.
Creating a RESTful controller in Laravel 4
POST = store() (Create a new entry)
DELETE = destroy($id) (Delete an entry)
GET = index() (Get all entries)
GET = show($id) (Get one entry)
PUT = update($id) (Update an entry)
The best extension for testing your API's:
Chrome extension Postman REST client
This is my simple router and controller, I did the same kind of project. You might want to try Postman RESTful client for Chrome to test your API,
routes.php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/
// Route group for API versioning
Route::group(array('prefix' => 'api/v1'), function() {
Route::resource('bookmarks', 'BookmarkController',
array('except' => array('create', 'edit')));
});
BookmarkController.php
class BookmarkController extends Controller {
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index() {
return Bookmark::all();
}
/**
* Store a newly created resource in storage.
*
* @return Response
*/
public function store() {
$bookmark = new Bookmark;
$bookmark->url = Input::get('url');
$bookmark->description = Input::get('description');
$bookmark->tags = Input::get('tags');
$bookmark->save();
return $bookmark;
}
/**
* Display the specified resource.
*
* @param int $id
* @return Response
*/
public function show($id) {
return Bookmark::find($id);
}
/**
* Update the specified resource in storage.
*
* @param int $id
* @return Response
*/
public function update($id) {
$bookmark = Bookmark::find($id);
$bookmark->url = Input::get('url');
$bookmark->description = Input::get('description');
$bookmark->tags = Input::get('tags');
$bookmark->save();
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return Response
*/
public function destroy($id) {
$bookmark = Bookmark::find($id)->delete();
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…