Laravel 不会解析模型

Laravel won't resolve model

我正在构建一个应用程序来跟踪费用,使用 laravel 5.8 作为后端。 当我尝试访问我的控制器上的 show 方法时,我发现 laravel 给我一个新的模型实例,而不是获取与提供的 ID 匹配的实例。

我尝试检查从 URI 获取的实际值,这是正确的,并且还手动查询以查看它是否有任何结果,确实如此。 我还检查了所有正确书写的名称(检查复数和单数)。

使用 return Expense::all() 的索引方法工作得很好。

模型是空的,它只有一个 $guarded 属性。

这是位于 routes/api.php

的路由文件
Route::apiResource('expenses', 'ExpenseController');

这是位于app/Http/Controllers/ExpenseController的控制器。php

namespace App\Http\Controllers;

use App\Models\Expense;

class ExpenseController extends Controller
{
    public function show(Expense $expense)
    {
        return Expense:findOrFail($expense->getKey()); // key is null since it's a fresh model
    }
}
public function show($expense)
{
    //dd($expense); //Shows the id given on the URI
    return Expense::where('id', $expense)->firstOrFail(); //Works!
}

费用模型

namespace App\Models;

use App\Model;

class Expense extends Model
{
    protected $guarded = [
        'id'
    ];
}

我希望获得具有给定 ID 的模型的 JSON 数据,但我得到的是 $exists = false 的新模型,没有收到任何 404 错误。

我也在使用 laravel/telescope,它显示请求以 200 代码完成并且没有进行任何查询。

使用dd时的响应

Expense {#378 ▼
  #guarded: array:1 [▶]
  #connection: null
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: false
  +wasRecentlyCreated: false
  #attributes: []
  #original: []
  #changes: []
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #fillable: []
}

这是整个classapp\Model.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model as BaseModel;

/**
 * Class Model
 * @package App
 * @method static static|null find($id)
 * @method static static findOrFail($id)
 * @method static static create(array $data)
 * @method static Collection all()
 */
class Model extends BaseModel
{

}

修复:我在 RouteServiceProvider 中缺少网络中间件

由于我使用 routes/api.php 文件作为我的路线,我需要更改 api 中间件到位于 app/Providers.

中的 RouteServiceProvider 文件中的 web 中间件

需要更改的代码:

/**
     * Define the "api" routes for the application.
     *
     * These routes are typically stateless.
     *
     * @return void
     */
    protected function mapApiRoutes()
    {
        Route::prefix('api')
             //->middleware('api')
             ->middleware('web')
             ->namespace($this->namespace)
             ->group(base_path('routes/api.php'));
    }