Search code examples
phplaravellaravel-routing

Laravel Routing Group - use value in Controller


All my requests are starting with a prefix, so I created a Route Group with multiple endpoints:

routes/web.php

Route::group(array('prefix' => $prefix), function() { 
    Route::get("/test/test2/{lang}", ['uses' => 'TestController@test2']);
    ...
});

Controller:

class TestController {
  public function test2(Request $request, $lang) {}
}

With the following test URL:

domain.com/customprefix/test/test2/en

I reach my controller and can access $lang (=en). But how can I pass $prefix to my controller methods? (It should evaluate to "customprefix" in this example)

Unfortunately I didn't find information about that in the documentation or in the API specification.


Solution

  • In your Controller you can get prefixes as one of these solutions:

    1.With $reques:

     public function TestController(\Illuminate\Http\Request $request)
    {
      $request->route()->getPrefix();
    }
    

    2.Without $request:

    $this->getRouter()->getCurrentRoute()->getPrefix()