Gar*_*ine 9 string url friendly-url slug laravel-4
看看我的前端URL生成的Str :: slug,但只是想知道你们如何用路由等来实现它,例如,你们如何将http://www.example.com/courses/1更改为http ://www.example.com/courses/this-course
Gar*_*ine 11
好的,我是这样做的:
// I have a slug field in my courses table and a slug field in my categories table, along with a category_id field in my courses table.
// Route
Route::get('courses/{categorySlug}/{slug?}', function($categorySlug, $slug) {
$course = Course::leftJoin('categories', 'categories.id', 'courses.category_id')
->where('categories.slug', $categorySlug)
->where('courses.slug', $slug)
->firstOrFail();
return View::make('courses.show')->with('course', $course);
});
Run Code Online (Sandbox Code Playgroud)
奇迹般有效.它获取$ categorySlug和$ slug变量然后使用它们来过滤Eloquent模型课程以从数据库中获取正确的课程对象.
编辑:您可以在视图中生成一个URL,如:
http://www.example.com/courses/it-training/mcse
通过做类似的事情:
<a href="{{ URL::to('courses/'.$course->category->parentCategorySlug($course->category->parent_id).'/'.$course->category->slug.'/'. $course->slug) }}" title="{{ $course->title }}">{{ $course->title }}</a>
Run Code Online (Sandbox Code Playgroud)
A在我的类别中有一个方法,如下所示,检索父类别slug.虽然使用某种类型的演示者类可以让你简单地使用$ course-> url,但是我还没有完成这项工作,这可以更好地实现.我会更新答案.
public function parentCategorySlug($parentId)
{
if ($parentId === '0')
{
return $this->slug;
}
return $this->where('id', $parentId)->first()->slug;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
25799 次 |
最近记录: |