【问题标题】:How to automatically resolve an id to a model instance in a Laravel route如何在 Laravel 路由中自动将 id 解析为模型实例
【发布时间】:2014-12-09 23:06:06
【问题描述】:

使用 Laravel 5 (dev / master) 是否可以让 laravel 自动加载带有 id 的 DI Eloquent 模型?类似于 Symfony 2 注释的东西。

class MyController {
  public function show($id, MyModel $model) {
      // I'm hoping $model->id == $id if it exists
  }
}

【问题讨论】:

    标签: php laravel laravel-5


    【解决方案1】:

    是的,它叫Route Model Binding

    在您的RouteServiceProvider::before 方法中,使用$router->model 进行设置:

    public function before(Router $router, UrlGenerator $url) {
        $router->model('user', 'User');
    }
    

    然后,只要您有一个名为 user 的参数,它就会自动替换为 User 的实例。

    【讨论】:

    • 无论如何要通过 laravel 5 中的注释来做到这一点,比如 symfony @ParamConverter 注释?
    • 我不这么认为。如果有,我相信至少会在文档中提及。
    猜你喜欢
    • 2016-09-24
    • 1970-01-01
    • 2019-09-24
    • 2021-10-05
    • 2022-11-12
    • 2016-06-14
    • 1970-01-01
    • 2019-08-25
    • 2019-06-06
    相关资源
    最近更新 更多