繁体   English   中英

laravel 5.5资源restful API

[英]laravel 5.5 resource restful API

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

我尝试命中端点时收到错误。

下面是我的路线/ 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.

由于api路由中的路由,请使用此URI:

https://example.com/api/cars

此外,正如我在我的最佳实践回顾中所展示的那样, 您不应该将逻辑放入路径中 ,而是将所有逻辑移动到控制器中。

使用api前缀 -

127.0.0.1:8000/api/cars 

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

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

如果您使用的是Laravel api.php那么您必须使用api前缀,

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

在Laravel: localhost:8000/api/yoururl

在Lumen: localhost/yoururl

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

您可能需要检查App\\Providers\\RouteServiceProvider@mapApiRoutes以获取更多信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM