我喜欢在 Laravel 中使用资源控制器,因为它让我思考数据建模。到目前为止,我\xe2\x80\x99m已经过去了,但我\xe2\x80\x99m现在在一个具有公共前端和受保护后端(管理区域)的网站上工作。
\n\n我\xe2\x80\x99ve创建了一个路由组,它添加了\xe2\x80\x9cadmin\xe2\x80\x9d前缀,如下所示:
\n\nRoute::group(array(\'before\' => \'auth\', \'prefix\' => \'admin\'), function()\n{\n Route::resource(\'article\', \'ArticleController\');\n Route::resource(\'event\', \'EventController\');\n Route::resource(\'user\', \'UserController\'); \n});\nRun Code Online (Sandbox Code Playgroud)\n\n我可以使用默认 URL 结构访问这些方法,即http://example.com/admin/article/1/edit。
\n\n但是,我希望在前端使用不同的URL 结构,这不符合资源控制器的期望。
\n\n例如,要访问一篇文章,我\xe2\x80\x99d喜欢使用如下URL:http://example.com/news/2014/06/17/some-article-slug。如果这篇文章的 ID 为 1,它应该(在幕后)转到/article/1/show。
\n\n我怎样才能在 Laravel 中实现这一目标?在其中,我可以对路线进行某种预处理,以将日期和段与文章 ID 相匹配,然后将其作为参数传递给我的资源控制器\xe2\x80\x99sshow()方法?
重新访问这个,我通过使用route\xe2\x80\x93model绑定和模式解决了它:
\n\n$year = '[12][0-9]{3}';\n$month = '0[1-9]|1[012]';\n$day = '0[1-9]|[12][0-9]|3[01]';\n$slug = '[a-z0-9\\-]+';\n\n// Pattern to match date and slug, including spaces\n$date_slug = sprintf('(%04d)\\/(%02d)\\/(%02d)\\/(%s)', $year, $month, $day, $slug);\n\nRoute::pattern('article_slug', $date_slug);\n\n// Perform the route\xe2\x80\x93model binding\nRoute::bind('article_slug', function ($slug) {\n return Article::findByDateAndSlug($date_slug);\n});\n\n// The actual route\nRoute::get('news/{article_slug}', 'ArticleController@show');\nRun Code Online (Sandbox Code Playgroud)\n\n然后注入一个Article根据需要将模型实例注入到我的控制器操作中。
| 归档时间: |
|
| 查看次数: |
5244 次 |
| 最近记录: |