2

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

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

index 方法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: []
}

这是整个类app\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 中缺少 Web 中间件

4

1 回答 1

1

由于我使用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'));
    }
于 2019-09-09T18:44:51.837 回答