简体   繁体   中英

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?

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);
}

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
}

If you don't need the names of the routes like in your example

->name('foobarPage');

you can use something like this

Route::get('{page_name}','PagesController@view')->where('page_name', '(about)|(foobar)');

This will accept only the values passed in the regular expression for the page_name parameter. Other routes will throw a 404 error. I should mention that this technique seems to be valid for applications with one level of url nesting only and should NOT be used as a pattern.

From what I can see above if all you are doing is showing the correct view I would go for

Route::get('{page}', function($page)
{
    if (view()->exists($page)) { 
        return view($page);
    } 
    return abort(404);
});

This prevents you even needing a method in your controller.

The accepted answer is what you want based on what you are doing.

If you really wanted a hardcoded value you can use the 'actions' array part of the route if you wanted.

Route::get('something', ['uses' => 'Controller@page', 'page' => 'something']);

public function page(Request $request)
{
    $page = $request->route()->getAction()['page'];
    ...
}

asklagbox - blog - random tips and tricks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM