user1327 user1327 - 4 months ago 20
PHP Question

Proper way to pass a hard-coded value from route to controller (Laravel)?

I have a

PagesController
with one action:
view
.
This action accepts a
page
argument.

What I want to achieve:

Have a routes
example.com/about
and
example.com/foobar
.
When one of this routes is triggered, pass a value predefined in routes file to
PagesController@view
.

In my routes file:

Route::get('about', function () {
return App::make('App\Http\Controllers\PagesController')->view('about');
})->name('aboutPage');

Route::get('foobar', function () {
return App::make('App\Http\Controllers\PagesController')->view('foobar');
})->name('foobarPage');


It works as expected, but I want to know is there a better and more proper way to achieve the same functionality?

Answer

Pass your pages as route parameter:

Route::get('{page}', 'PagesController@view');

//controller
public function view($page)
{
    //$page is your value passed by route;
    return view($page);
}
Comments