路由模型绑定无法从id

时间:2019-05-07 07:38:26

标签: php laravel routing

我正在Laravel 5.7中构建一个应用程序。我已经在routes/api.php文件中设置了一条与用户模型绑定的路由。当我将现有的用户ID传递到路由时,它将被解析为空白用户模型。

我相信我已经遵循laravel标准,通过在控制器中键入用户模型的方式提示了。

routes / api.php

Route::prefix('role-permissions')->group(function () {
    Route::get('by-user/{user}', 'RolePermissionsController@getByUserId')->name('api.role-permissions.by-user');
});

app / Http / Controllers / RolePermissionsController.php

public function getByUserId(User $user)
{
    dd($user);
    return $this->getAsResourceCollection($this->repository->getByUserId($user));
}

dd($user);返回一个空白的User对象

预期:具有正确ID的已填充用户模型 我可以确认表格中是否存在ID为1的用户

实际:

User {#375
  #fillable: array:3 [
    0 => "name"
    1 => "email"
    2 => "password"
  ]
  #hidden: array:2 [
    0 => "password"
    1 => "remember_token"
  ]
  #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
  #visible: []
  #guarded: array:1 [
    0 => "*"
  ]
  #rememberTokenName: "remember_token"
  #accessToken: null
}

3 个答案:

答案 0 :(得分:0)

我在mapApiRoutes中删除了RouteServiceProvider方法中的api中间件路由

答案 1 :(得分:0)

我不认为$ user应该是对象。这是在route中传递的参数,因此代码应为:

public function getByUserId($user)
{
    dd($user);
    return $this->getAsResourceCollection($this->repository->getByUserId($user));
}

答案 2 :(得分:0)

这样在路由中添加“绑定”中间件将解决此问题:

Route::prefix('role-permissions')->middleware('bindings')->group(function () {
    Route::get('by-user/{user}', 'RolePermissionsController@getByUserId')->name('api.role-permissions.by-user');
});