【问题标题】:Friendly urls in Laravel , am I doing it right?Laravel 中的友好网址,我做对了吗?
【发布时间】:2014-02-26 22:50:30
【问题描述】:

这是我的路线:

Route::get('location/{id}/{title?}', array('as' => 'scouting_single', 'uses' => 'ScoutingController@get_single')); 

类很简单:

public function get_single($id, $title ='') { 
    $location = new Location; 
    if(is_numeric($id)) { 
        $location = $location->find($id);
        if(isset($location)) {
            $author = User::find($location->author);                
            $meta = $location->find($id)->metakeywords;

            if($title == '') { 
                $slug = Str::slug($location->title); 
                return Redirect::to('location/'.$id.'/'.$slug);
            }


            return View::make('scoutingviews.view')->with('pagetitle', 'Location view')
                ->with('location', Location::find($id))
                ->with('author', $author)
                ->with('meta', $meta);  
        } else { 
            return Redirect::to('/')->with('message', 'That record is not available'); 
        }               
    } else { 
        return Redirect::to('404');
    }
}

一切似乎都很好,但在四处搜索之后,似乎其他人的做法有所不同,比如将 slug 保存到 db,但我只想将 id 包含到 url 中......并使其可选包含标题 slug .如果用户删除了 slug,它无论如何都会用 slug 重定向用户。

我还在学习 laravel,所以请原谅关于 seo 友好性的新手问题,我只是不希望 /{id}/ 和 /{id}/{title} 算作重复

【问题讨论】:

  • 我注意到您的包含标题的 URL 似乎也包含 ID。这不是多余的吗?我原以为你会想要:location/{id}location/{title}?

标签: php laravel seo laravel-routing


【解决方案1】:

如果您担心 SEO,那么在数据库中添加 URL slug 是您的最佳选择。在 URL 中包含 ID 对搜索引擎或用户没有多大帮助。这也应该简化您的代码。除此之外,您应该查看Eloquent relationships,您可以在其中将用户附加到位置。而不是拥有

$author = User::find($location->author);

你可以有

$author = $location->author;

关系将是用户hasMany 位置和位置belongsTo 用户。这也是假设用户可以拥有许多位置。

【讨论】:

  • 我猜 db 可能是最好的,我发现 slug 不会经常被重命名。我会在下一个项目中记住这一点,谢谢!
猜你喜欢
  • 1970-01-01
  • 2011-08-11
  • 1970-01-01
  • 1970-01-01
  • 2012-10-15
  • 2011-02-15
  • 2013-03-03
  • 1970-01-01
  • 2015-08-13
相关资源
最近更新 更多