Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 213
user1327 Avatar asked Dec 04 '25 21:12

user1327


2 Answers

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);
}
like image 124
Phargelm Avatar answered Dec 06 '25 13:12

Phargelm


So you just want an argument to your action. You can use optional parameters if that argument can be empty. You can read more about it here.

Route::get('{argument?}', 'PagesController@view')->name('page');

And in your PagesController:

public function view($argument = 'default') {
    // Your logic
}
like image 40
Can Vural Avatar answered Dec 06 '25 12:12

Can Vural