Pablo
Pablo

Reputation: 1435

Laravel 5.1 Route::controller with optional url params?

I have this code in routes

Route::controller('/orders/{from}/{to}', 'CartController');

the link something like this

localhost/admin/orders/2020-01-01/2020-01-02

this will open all the records between 2 dates

But I have another link something like this

localhost/admin/orders/4212

to open specific row on a new tab

This 2 links falls for 1 function

called it

 public function getIndex($from,$to){


 }

can I do this params optional? with 1 Route::controller('/orders/{from}/{to}', 'CartController'); in my route.php?

Upvotes: 0

Views: 56

Answers (3)

A.A Noman
A.A Noman

Reputation: 5270

You can use this like

Route::controller('/orders/{from}/{to?}', 'CartController');

And in your controller

public function getIndex($from,$to=null){
    if($to==null){
        //to open specific row on a new tab
    }
    else{
        // Other task
    }

}

Upvotes: 0

Kalim
Kalim

Reputation: 499

Try this:

Route::controller('/orders/{from?}/{to?}', 'CartController');
public function getIndex($from = false,$to = false){


}

Upvotes: 0

zlatan
zlatan

Reputation: 3951

You can set any of your parameters to be optional, just by appending ? at the end of the parameter name. Simple example:

Route::controller('/orders/{from?}/{to?}', 'CartController');

Also, I jut noticed that you don't call any of your controller actions in your route definition. If you want this route to lead to your getIndex() method, change it to this:

Route::controller('/orders/{from?}/{to?}', 'CartController@getIndex');

Read more on official documentation.

Upvotes: 2

Related Questions