How To Implement "defaults()" For Multiple Params In A Route - Laravel

Viewed 268

So I have a POST URL with two parameters and I want to assign default values for both parameters .

I know you can implement this way for a URL with a single param:

Route::post('activity-log/datatable/{tag_access?}/{page_access?}',
'SettingsController@datatable_activity_log')
->defaults('tag_access', 'activity-log');

But how do i go about it with a URL that looks like this:

Route::post('activity-log/datatable/{tag_access?}/{page_access?}',
'SettingsController@datatable_activity_log')
2 Answers

You can achieve it by following way:

Keep your route as you want like this:

Route::post('activity-log/datatable/{tag_access?}/{page_access?}','SettingsController@datatable_activity_log')

Now, In controller function you can take these parameters with default value like this,

public function datatable_activity_log($tag_access='activity-log', $page_access='activity-log', Request $request){
    // Here write your logic
}

This may not be the best way to achieve what you want but this is one of the way.

From what I see regarding the usage of defaults you can either do one at a time:

Route::post('activity-log/datatable/{tag_access?}/{page_access?}',
'SettingsController@datatable_activity_log')
->defaults('tag_access', 'activity-log')
->defaults('page_access', 'defaultValue');

An alternative (since defaults is public) is to do:

$route = Route::post('activity-log/datatable/{tag_access?}/{page_access?}',
'SettingsController@datatable_activity_log');
$route->defaults = [ 'tag_access' => 'activity-log', 'page_access' => 'defaultValue' ];

My personal favourite is what @Sagar Gautam suggest which is to use default function parameters.

Related