【问题标题】:Laravel blog slug route definitionLaravel 博客 slug 路由定义
【发布时间】:2017-09-09 02:47:05
【问题描述】:

我正在关注博客教程,发现这条有趣的博客路线用于显示博客文章

http://sweet-blog.herokuapp.com/interesting-articles-wide-pharmaceutical-and-produts

这是迁移文件https://github.com/28harishkumar/blog/blob/master/database/migrations/2015_05_23_133926_posts.php

这是https://github.com/28harishkumar/blog/blob/master/app/Http/Controllers/PostController.php#L85函数

public function show($slug)
{
    $post = Posts::where('slug',$slug)->first();
    if($post)
    {
        if($post->active == false)
            return redirect('/')->withErrors('requested page not found');
        $comments = $post->comments;    
    }
    else 
    {
        return redirect('/')->withErrors('requested page not found');
    }
    return view('posts.show')->withPost($post)->withComments($comments);
}

这是路线

https://github.com/28harishkumar/blog/blob/master/app/Http/routes.php#L62

Route::get('/{slug}',['as' => 'post', 'uses' => 'PostController@show'])->where('slug', '[A-Za-z0-9-_]+');

当我看到这行时

public function show($slug)
{
    $post = Posts::where('slug',$slug)->first();

laravel 是否在不使用$request 获取 uri 段的情况下为我们获取 slug?

如果是这样,我们将如何处理 uri 中的多个参数?

【问题讨论】:

  • 使用/ 分隔参数,如/{$slug}/{$param}
  • laravel 获取 uri 段 slug 了吗?
  • 是的,$slug 参数将包含 url 中的 slug,另外您需要将默认值传递给 $slug 变量 laravel.com/docs/5.4/routing#route-parameters
  • 在您的/{$slug}/{$param} 中我将如何访问参数?
  • public function show($slug = null, $param = null) { // you'll be able to access the $param variable in here

标签: laravel


【解决方案1】:

uri中的多个参数可以为:

Route::get('/{slug}/{other}',['as' => 'post', 'uses' => 'PostController@show'])->where('slug', '[A-Za-z0-9-_]+');

在这里,我使用 other 作为此 uri 的第二个参数。您可以根据需要使用许多参数。 在控制器中:

public function show($slug, $other) {
 // Your code here   
}

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2018-12-21
    • 1970-01-01
    • 2017-01-10
    • 2013-11-05
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多