繁体   English   中英

Laravel中的动态页面路线

[英]Dynamic Pages routes in Laravel

这个问题似乎非常简单,但是我无法弄清楚...您如何在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条或更多条路线?

好的,基本上,您想要一个类别的类别,并希望能够通过这些类别访问帖子。 我假设您有一个这样的模型:

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长度不受限制,但过长则是不好的做法,这种方法对CRUD不利-使用Route::resource代替,循环看起来很痛苦。

请注意Route::controllerRoute::resource更加狂野,您必须按以下顺序将条目放入route.php中: Route::<http verb>Route::resource然后是Route::controller 到目前为止,我遇到了Laravel路由行为,即使它没有关于所请求url的方法并抛出NotFoundHttpException ,它也会戳Route::controller 因此,如果在Route::controller laravel之后有Route::<http verb> ,则根本不会触摸它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM