Ok, so basically you want to have a categories of categories and able to access posts through those categories. I assume you had a model like this:
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');
}
}
then on create a controller to retrieve posts
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
}
}
Then add to your route.php
:
Route::controller('/','PageLoaderController', [
'getIndex' => 'home'
]);
That should do. However, this is a dirty approach which is i won't suggest using this thing extensively. Some of the reasons are, http get length is not limited but it's a bad practice to have it too long, this approach is not good for CRUD - go for Route::resource
instead, also the loop looks painful.
Take note: Route::controller
is more wild than Route::resource
you had to put entries in route.php
in this order Route::<http verb>
, Route::resource
then finally Route::controller
. So far, i faced Laravel route behavior, it'll poke Route::controller
even if it had no method regarding requested url and throws a NotFoundHttpException
. So if you had Route::<http verb>
after Route::controller
laravel tend to not touch it at all.