Skip to content
Advertisement

Laravel 7: Generate named view-routes from blade files in directory

Is there a nice way, to solve this issue: I have a folder ressources/views/project/content with several blade teplates, let’s say:

home.blade.php
how-to.blade.php
info.blade.php
best-way-to-score.blade.php
...

Right now, I define one view route per file:

Route::view('/home', 'project.content.home')->name('home');
Route::view('/how-to', 'project.content.how-to')->name('how-to');
...

How can I create these routes on thy fly? I could solve it with a loop through all files in this directory, but maybe there is a more elegant way/function in laravel I don’t know yet?

Advertisement

Answer

If I understand correctly, what you you need is a generic get route like this:

Route::get('/{page}', 'PageController@show');

and then you need a PageController with a function to return the requested page:

public function show($page)
{
    return view('project.content.'.$page);
}

Just have in mind that this kind of route will “catch” every get request so put it at the end of the web.php file

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement