这个问题看起来很简单,但我无法理解......你如何在Laravel 5.1中使用类别实现基于slug的动态页面?
像mywebsite.com/category/sub-category/my-page
我知道Route::get('/{slug}')
给出了“slug”作为标识符,但问题是页面可能位于mywebsite.com/category/my-page
,所以如果将路由设置为Route::get('/{category}/{subcategory}/{page}')
之类的话不适用于第二个例子。
我正在考虑制作像
这样的3条路线Route::get('/{category}/{subcategory}/{page}')
Route::get('/{category}/{page}')
Route::get('/{page}')
然后控制器接收($category = null, $subcategory = null, $page = null)
在控制器中就像
if (!$page)
$page = $subcategory;
if (!$page)
$page = $category;
还有另一种更清洁的方法来实现这一目标吗?因为这里我们只有2个类别路线,但可能有3个,5个或更多?
答案 0 :(得分:0)
好的,基本上你想拥有一个类别类别,并且能够通过这些类别访问帖子。我假设你有一个这样的模型:
class Category extends Model
{
public function SubCategories()
{
return $this->hasMany('Category', 'parent_id', 'id');
}
public function ParentCategory()
{
return $this->belongsTo('Category', 'parent_id', 'id);
}
public function Page()
{
return $this->hasMany('Page', 'category_id', 'id');
}
}
然后创建一个控制器来检索帖子
class PageLoaderController extends Controller
{
//assumes you want to run this via root url (/)
public function getIndex(Requests $request)
{
//this practically get you any parameter after public/ (root url)
$categories = $request->segments();
$countSeg = count($categories);
$fcategory = null;
$fpage = null;
for($i = 0; $i < $countSeg; $i++)
{
//this part of iteration is hypothetical - you had to try it to make sure it had the desired outcome
if(($i + 1) == $countSeg)
{
//make sure fcategory != null, it should throw 404 otherwise
//you had to add code for that here
$fpage = $fcategory->Page()->where('slug', $categories[$i])->firstOrFail();
}
elseif($i == 0)
{
//find initial category, if no result, throw 404
$fcategory = Category::where('slug', $categories[0])->firstOrFail();
}
else
{
//take it's child category if possible, otherwise throw 404
$fcategory = $fcategory->SubCategories()->where('slug', $categories[$i])->firstOrFail()
}
}
//do something with your $fpage, render it or something else
}
}
然后添加到您的route.php
:
Route::controller('/','PageLoaderController', [
'getIndex' => 'home'
]);
应该这样做。然而,这是一个脏方法,我不建议广泛使用这个东西。其中一些原因是,http get length并不受限制,但这种做法太长,这种做法对CRUD不利 - 转而使用Route::resource
,循环看起来也很痛苦
请注意:Route::controller
比Route::resource
更加狂野,您必须按此顺序route.php
Route::<http verb>
添加条目Route::resource
,{{1}最后Route::controller
。到目前为止,我面对Laravel路线行为,即使它没有关于请求的网址的方法并且抛出Route::controller
,它也会戳NotFoundHttpException
。因此,如果您在Route::<http verb>
laravel之后Route::controller
倾向于根本不接触它。{/ p>