Answer the question
In order to leave comments, you need to log in
How to do routes in Laravel 8 specific pages from Database?
I'm learning Laravel now, I started with version 8, in many courses everyone does primitive things, create a main page and a post page. But they do n’t say how to make specific pages like site.ru /about/ .
So the question is, there is a table with pages in the database, each page has a SLUG, when a request is made to the router, SLUG is transmitted further in the controller, I check whether there is such a page in the database, if there is, I display it, if not, I send it to 404, this is done in order to so that I don't write manually into routes every time like /about/, /about2/, /about3/ .... /about9999/.
Am I understanding the implementation correctly? If not, tell me how to do it right...
web.php
Route::get('/{page:slug}', '[email protected]')->name('page.single')->middleware('shortcode');
class PageController extends Controller
{
public function index()
{
$data = Page::with('layout')->where('slug', 'home-page')->firstOrFail();
$data->views += 1;
$data->update();
$data['thumbnail_url'] = $data->getImage();
return view(
"front.pages.{$data->layout->tpl}",
compact('data'));
}
public function show($slug)
{
if ($slug === 'home-page'){
return Redirect::route('home');
}
$data = Page::where('slug', $slug)->firstOrFail();
$data->views += 1;
$data->update();
return view(
"front.pages.{$data->layout->tpl}",
compact('data'));
}
}
Answer the question
In order to leave comments, you need to log in
Well, in general, everything looks right, if you want to do just that.
Little by little:
$data->increment('views')
, if you want your statistics to be calculated correctly.This implementation is no different from the posts page. The same show method of the Page resource. It's right to do so.
Route::get('/pages/{page:slug}', '[email protected]')->name('pages.show');
public function show(Page $page)
{
$page->increment('views');
return view('page.show', compact('page'));
}
But they don’t say how to make specific pages like site.ru/about/.
Route::view('about', 'page.about')->name('about');
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question