【问题标题】:Laravel 8 API : Get with id return empty jsonLaravel 8 API:获取 id 返回空 json
【发布时间】:2021-09-10 06:56:39
【问题描述】:

我有一个非常大的问题,我尝试使用 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);

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

【问题讨论】:

    标签: laravel api laravel-8


    【解决方案1】:

    改成

    public function show(Facts $fact)
    {
    
       return $fact;
    }
    

    验证运行

    php artisan route:list
    

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

    例如

    api/facts/{fact}   | facts.show
    

    【讨论】:

    • 这正是我在我的路线中所拥有的......我会努力改变事实
    • @VincentB.你还有问题吗?
    • 非常感谢,它有效!只是为了事实的“s”,顺便说一句 laravel 单独写它...... xD 谢谢大家!
    猜你喜欢
    • 2022-07-11
    • 1970-01-01
    • 2021-01-09
    • 2021-08-12
    • 1970-01-01
    • 2018-11-06
    • 2021-05-22
    • 2016-06-28
    • 1970-01-01
    相关资源
    最近更新 更多