如何在Laravel中创建RESTful API以在我的BackboneJS应用程序中使用

sid*_*ber 1 api rest backbone.js laravel laravel-4

我想在Laravel 4中创建一个RESTful API,以便在我的BackboneJS应用程序中使用.这样做的最佳方式是什么?Laravel 4框架是否为此提供了良好的解决方案.

sid*_*ber 5

这是创建存储书签的API的示例.它使用该Route::resource()方法.

在Laravel 4中创建RESTful控制器

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)
Run Code Online (Sandbox Code Playgroud)

测试API的最佳扩展: Chrome扩展Postman REST客户端

这是我简单的路由器和控制器,我做了同样的项目.您可能想尝试使用Postman RESTful客户端来测试您的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')));
});
Run Code Online (Sandbox Code Playgroud)

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();
     }

}
Run Code Online (Sandbox Code Playgroud)