Andrew Vershinin
Andrew Vershinin

Reputation: 147

Laravel routing: how to pass parameter to controller (not via URL)?

I have two routes: A/{param}/C and B/{param}/C. Also I have a controller with method:

public function index($param, $param1 = false)
{
    //...
}

In case of A/{param}/C I pass only one parameter - one specified in URL, and the function uses the default for second one. In case of the second route, I want to pass true as second parameter. Since it isn't specified in URL, how to pass it to the function?

Upvotes: 1

Views: 16028

Answers (1)

c-griffin
c-griffin

Reputation: 3026

If i understand you correctly, without using $_POST, you won't be able to pass a parameter without be being somewhere in the URI (outside of setting a session variable, which i wouldn't advise)

Another option may be to pass it as a query string parameter. It will still be in the url, but won't necessarily be caught in the route pattern

URLs:

A/{param}/C
B/{param}/C?param1=true

--
Controller:

public function index($param)
{

   $param1 = Request::query('param1'); // if not present false, if present, {value}

}

--

Alternatively, if you'd like a friendly URL, you can place a question mark after your second parameter, indicating that it may or may not exist. This will match both of the below URLs

URL:

A/{param}/C
B/{param}/C/true

Route:

Route::get('B/{param}/C/{param1?}', 'YourController@index');

Controller:

public function index($param, $param1 = false)
{
   //
}

Upvotes: 2

Related Questions