Laravel 从 REST API 检索数据

新手上路,请多包涵

好的,所以我有以下情况:

我正在构建的系统是从 REST api 检索数据并将该数据保存到数据库中。我想知道的是如何实现这一点,以及这种行为在 Laravel 结构(控制器、模型等)的意义上会在哪里? Laravel 是否有内置机制来从外部来源检索数据?

原文由 Tomkarho 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 497
2 个回答

首先你必须在你的 app/routes.php

 /*
    API Routes
*/

Route::group(array('prefix' => 'api/v1', 'before' => 'auth.basic'), function()
{
    Route::resource('pages', 'PagesController', array('only' => array('index', 'store', 'show', 'update', 'destroy')));
    Route::resource('users', 'UsersController');
});

注意: 如果API调用不需要认证,可以去掉 'before' => 'auth.basic'

在这里,您可以从您的 PagesController 访问 index, store, show, update and destroy 方法。

请求网址将是,

 GET http://localhost/project/api/v1/pages // this will call index function
POST http://localhost/project/api/v1/pages // this will call store function
GET http://localhost/project/api/v1/pages/1 // this will call show method with 1 as arg
PUT http://localhost/project/api/v1/pages/1 // this will call update with 1 as arg
DELETE http://localhost/project/api/v1/pages/1 // this will call destroy with 1 as arg

命令行 CURL 请求将是这样的(这里的用户名和密码是 admin )并假设你有 .htaccess 文件要删除 index.php

 curl --user admin:admin localhost/project/api/v1/pages
curl --user admin:admin -d 'title=sample&slug=abc' localhost/project/api/v1/pages
curl --user admin:admin localhost/project/api/v1/pages/2
curl -i -X PUT --user admin:admin -d 'title=Updated Title' localhost/project/api/v1/pages/2
curl -i -X DELETE --user admin:admin localhost/project/api/v1/pages/1

接下来,您的 app/controllers 文件夹中有两个名为 PagesController.phpUsersController.php 的控制器。

PagesController.php,

 <?php

class PagesController extends BaseController {

    /**
     * Display a listing of the resource.
     *
     * @return Response
     * curl --user admin:admin localhost/project/api/v1/pages
     */

    public function index() {

        $pages = Page::all();;

        return Response::json(array(
            'status' => 'success',
            'pages' => $pages->toArray()),
            200
        );
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     * curl --user admin:admin -d 'title=sample&slug=abc' localhost/project/api/v1/pages
     */

    public function store() {

        // add some validation also
        $input = Input::all();

        $page = new Page;

        if ( $input['title'] ) {
            $page->title =$input['title'];
        }
        if ( $input['slug'] ) {
            $page->slug =$input['slug'];
        }

        $page->save();

        return Response::json(array(
            'error' => false,
            'pages' => $page->toArray()),
            200
        );
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     * curl --user admin:admin localhost/project/api/v1/pages/2
     */

    public function show($id) {

        $page = Page::where('id', $id)
                    ->take(1)
                    ->get();

        return Response::json(array(
            'status' => 'success',
            'pages' => $page->toArray()),
            200
        );
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  int  $id
     * @return Response
     * curl -i -X PUT --user admin:admin -d 'title=Updated Title' localhost/project/api/v1/pages/2
     */

    public function update($id) {

        $input = Input::all();

        $page = Page::find($id);

        if ( $input['title'] ) {
            $page->title =$input['title'];
        }
        if ( $input['slug'] ) {
            $page->slug =$input['slug'];
        }

        $page->save();

        return Response::json(array(
            'error' => false,
            'message' => 'Page Updated'),
            200
        );
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     * curl -i -X DELETE --user admin:admin localhost/project/api/v1/pages/1
     */

    public function destroy($id) {
        $page = Page::find($id);

        $page->delete();

        return Response::json(array(
            'error' => false,
            'message' => 'Page Deleted'),
            200
        );
    }

}

然后你有名为 Page 的模型,它将使用名为 pages 的表。

 <?php

class Page extends Eloquent {
}

您可以使用 Laravel4 生成器使用 php artisan generator 命令创建这些资源。 在这里 阅读。

因此,使用此路由分组,您可以使用相同的应用程序来发出 API 请求并作为前端。

原文由 Anshad Vattapoyil 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可以选择使用什么:

  1. 暴饮暴食
  2. 卷曲
  3. 文件获取内容:
    $json = json_decode(file_get_contents('http://host.com/api/v1/users/1'), true);

推荐人

原文由 tsveti_iko 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题