Laravel 5 REST 客户端 CRUD

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28793403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:02:48  来源:igfitidea点击:

Laravel 5 REST client CRUD

phprestlaravellaravel-5

提问by basagabi

Is there a way in Laravel 5 to do a CRUD using REST? I have a REST API already using CodeIgniter and I want my Laravel application to communicate with it.

Laravel 5 有没有办法使用 REST 来做一个 CRUD?我有一个 REST API 已经在使用 CodeIgniter,我希望我的 Laravel 应用程序与它通信。

So let's say I have this url to get all gender: http://api.local/api/api_gender/gender

所以假设我有这个 url 来获取所有性别:http://api.local/api/api_gender/gender

In my controller, it seems I can do something like this:

在我的控制器中,我似乎可以做这样的事情:

$results = json_decode(file_get_contents('http://api.local/api/api_gender/gender/'));

But I dont know if this is the right way to do it.

但我不知道这是否是正确的做法。

Now, how could I do it if I want to add a new gender in Laravel? In CI, I could simply use Phil's rest library and just use $this->rest->put('http://api.local/api/api_gender/gender/', $parameters)

现在,如果我想在 Laravel 中添加一个新的性别,我该怎么做?在 CI 中,我可以简单地使用 Phil 的 rest 库,然后使用$this->rest->put('http://api.local/api/api_gender/gender/', $parameters)

回答by Jeroen Noten

I would use Guzzle, a very popular, flexible HTTP client for PHP. As far as I know, it is one of the most used packages to make HTTP requests in PHP.

我会使用Guzzle,这是一个非常流行的、灵活的 PHP HTTP 客户端。据我所知,它是 PHP 中最常用的 HTTP 请求包之一。

$client = new GuzzleHttp\Client();

$client->put('http://api.local/api/api_gender/gender/', ['json' => ['foo' => 'bar']]);
// or
$client->put('http://api.local/api/api_gender/gender/', ['query' => ['foo' => 'bar']]);