Answer the question
In order to leave comments, you need to log in
Create child pages via laravel 8 admin panel?
Now I am writing a test blog for myself, with an admin panel and everything is as it should be. At this stage, I want to implement the creation of pages (already done) and subpages for them.
The problem is that I don't quite understand how to properly write the database structure and logic for subpages. Do I need to create a separate migration or are there other ways?
Please tell me - how to properly organize routing through controllers, let's say for such things
Route::get('/{page-slug}', 'website\PageController');
Route::get('/{page-slug}/{sub-page-slug}', 'website\PageController');
public function up()
{
Schema::create('pages', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('url' )->unique();
$table->string('description');
$table->string('image')->nullable();
$table->longText('page_content')->nullable();
$table->integer('user_id')->unsigned();
$table->timestamp('published_at');
$table->timestamps();
});
}
Answer the question
In order to leave comments, you need to log in
First, add a parent_id (nullable, default null, links to pages->id) column to the pages table.
Second, in the Page model, set up links to pages (HasMany).
Regarding routes, one solution is URL parsing.
// routes/web.php в самом конце
Route::get('{slug}', '[email protected]')->where('slug', '([0-9A-Za-z-/]+)');
// прикладываю один из своих рабочих вариантов. тут парсятся не только страницы, но и категории (с мультивложенностью), продукты
// app/http/controllers/controller.php
public function parse(Request $request) {
$urlArray = explode('/', $request->path());
if (count($urlArray) === 1) {
$page = Page::where('slug', $urlArray[0])->first();
if (!empty($page)) {
return (new PageController)->show($page);
}
$category = Category::where('slug', $urlArray[0])->where('parent_id', 1)->first();
if (!empty($category)) {
return (new CategoryController)->show($request, (new ProductFilters($request)), $urlArray[0]);
}
} else {
$parentCategory = NULL;
$i = 1;
foreach ($urlArray as $urlArrayItem) {
$lastStep = $i === count($urlArray);
$category = Category::where('slug', $urlArrayItem);
if (is_null($parentCategory)) {
$category->where('parent_id', 1);
} else {
$category->where('parent_id', $parentCategory->id);
}
if (empty($category->first())) {
if ($lastStep) {
$product = $parentCategory->products()->where('slug', $urlArrayItem)->active()->first();
if (!empty($product)) {
return (new ProductController)->show($urlArrayItem);
}
}
abort(404);
} else {
if ($lastStep) {
return (new CategoryController)->show($request, (new ProductFilters($request)), $urlArrayItem);
}
$parentCategory = $category->first();
}
$i++;
}
}
abort(404);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question