首页 > 解决方案 > Laravel 8 API:获取 id 返回空 json

问题描述

我有一个非常大的问题,我尝试使用 Laravel 8 创建一个 API,但是当我使用 Get 方法来获取我所有的事实时,它可以工作并且我得到了所有的事实,但是当使用 id 时,我总是有空的 json ...

     * Display the specified resource.
     *
     * @param Facts $facts
     * @return Facts
     */
    public function show(Facts $facts)
    {
        dd($facts);
        return $facts;
    }

我得到这个而不是我的数据

App\Models\Facts {#1195
  #fillable: array:6 [
    0 => "type"
    1 => "deleted"
    2 => "text"
    3 => "used"
    4 => "verified"
    5 => "count"
  ]
  #connection: null
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  +preventsLazyLoading: false
  #perPage: 15
  +exists: false
  +wasRecentlyCreated: false
  #attributes: []
  #original: []
  #changes: []
  #casts: []
  #classCastCache: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #guarded: array:1 [
    0 => "*"
  ]
}

这是控制器上的路线。

Route::apiResource('facts', FactsController::class);

对不起,我的英语不是很完美,但如果你能帮助我,请...谢谢大家

标签: laravelapilaravel-8

解决方案


改成

public function show(Facts $fact)
{

   return $fact;
}

验证运行

php artisan route:list

即使您的 api 资源名称是复数facts,参数仍然是单数。

例如

api/facts/{fact}   | facts.show

推荐阅读