【问题标题】:What does Route::model mean in Laravel?Route::model 在 Laravel 中是什么意思?
【发布时间】:2017-03-07 09:15:57
【问题描述】:

任何人都可以解释这些行吗?它是如何工作的?

public function boot()
{
     parent::boot();

     Route::model('user', App\User::class);
}

接下来,定义一个包含{user}参数的路由:

$router->get('profile/{user}', function(App\User $user) {
  //
});

【问题讨论】:

标签: php laravel laravel-5 laravel-5.3 laravel-routing


【解决方案1】:

这叫Route Model Explicit Binding

有了这个:

Route::model('user', App\User::class);

您是说:当'user' 字符串在路由中用作参数时,为我创建一个App\User::class 模型,它与传递给路由的参数具有相同的ID。然后在路由方法处理程序上注入模型。

例如,url:'profile/10' 将匹配此路由:

$router->get('profile/{user}', function(App\User $user) {
  //
});

而 id 为 10 的 App\User 模型会被 Laravel 自动获取

从一般的角度来看,通常在您的路线中,您会执行以下操作:

public function edit($id)
{
    //fetch the user from db...
    $user = User::find($id);

    //do something with the $user...
}

您可以使用路由模型绑定:

public function edit(App\User $user)
{
    //do something with $user...
}

避免从数据库中获取模型:Laravel 会为你做这件事

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-18
    • 2019-01-02
    • 2012-08-15
    • 2018-04-25
    • 2019-01-15
    • 2011-08-12
    • 2017-06-11
    • 2018-03-05
    相关资源
    最近更新 更多