【问题标题】:laravel 5.5 resource restful APIlaravel 5.5 资源 RESTful API
【发布时间】:2018-01-24 07:36:39
【问题描述】:

我正在尝试为我的应用程序创建一个 API,以便我可以共享端点,并让一个应用程序作为具有业务逻辑的核心应用程序,而另一个可以与公开的端点连接以将功能用作服务。

我在尝试到达端点时遇到错误。

下面是我的route/api.php

<?php

use App\PostModell;
use App\Http\Resources\PostModellResource;
use Illuminate\Http\Request;

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});
Route::get( '/cars',function(){
    return new PostModellResource(PostModell::all());
}); 

我的资源类看起来像

class PostModellResource extends Resource
{
         public function toArray($request)
    {
        return
        [
            'id'=>$this->id,
            'title'=>$this->title,
            'body'=>$this->body,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,

        ];          
    }

错误是

Sorry, the page you are looking for could not be found.

【问题讨论】:

  • 您要访问哪个网址??向我们展示您尝试过的带有域名的完整网址,并收到类似www.google.com/lists 的错误
  • 这是127.0.0.1:8000/cars的网址
  • @DENNISKITHINJI 因为它在routes/app.php,你需要使用https://127.0.0.1:8000/api/cars
  • @Sohel0415 这工作127.0.0.1:8000/api/cars 但也收到一个新错误“此集合实例上不存在属性 [标题]。”这发生在我所有的模型列上
  • @DENNISKITHINJI 查看我的更新答案

标签: php laravel rest laravel-5 laravel-5.5


【解决方案1】:

使用api前缀-

127.0.0.1:8000/api/cars 

要转换资源集合,需要使用collection()方法-

return PostModellResource::collection(PostModell::all());

【讨论】:

    【解决方案2】:

    由于api路由中的路由,使用这个URI:

    https://example.com/api/cars
    

    另外,正如我在我的最佳实践 repo you shouldn't put the logic into routes 中所展示的,将所有逻辑移到控制器中。

    【讨论】:

      【解决方案3】:

      如果你使用 Laravel api.php 那么你必须使用 api 前缀,

      或者,如果您使用 Lumen web.php,那么您可以直接调用它,也可以根据您的要求定义 api 前缀。

      在 Laravel 中:localhost:8000/api/yoururl

      在流明中:localhost/yoururl

      【讨论】:

        【解决方案4】:

        api中的所有路由都有/api的前缀路径(默认)。因此,在您的情况下,您应该通过以下方式访问它:http://YOURAPPURL/api/cars

        您可能需要查看您的App\Providers\RouteServiceProvider@mapApiRoutes 以了解更多信息。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-06-14
          • 1970-01-01
          • 1970-01-01
          • 2018-03-05
          • 1970-01-01
          • 1970-01-01
          • 2018-08-08
          相关资源
          最近更新 更多