Deeven
Deeven

Reputation: 443

how to set default values for url parameters?

https://laravel.com/docs/5.5/urls#default-values

In the docs it says,

you may use the URL::defaults method to define a default value for this 
parameter that will always be applied during the current request.

I don't understand what current request is

I thought it is meant to be used as

route('route-name'); 

and the url should be generated with the parameters replaced with default values

Also the doc says it has to be done in the middleware

but middleware does operation on the requests but when I use the route helper I do not make any requests

Please help Example would be very helpful It may be that I miss understood something Please Help

Upvotes: 2

Views: 5192

Answers (3)

Ali A. Dhillon
Ali A. Dhillon

Reputation: 643

I tried to apply the middleware to the following route which require the default value of locale but it did not work.

Route::get('/{locale}/posts', function () {
    //
})->name('post.index')->middleware('locale');
// And Inside your Kernel.php 
 protected $routeMiddleware [
'locale' => \App\Http\Middleware\SetDefaultLocaleForUrls::class, ]

But it actually works if you instead apply this middleware to the Routes or Controllers which uses the route('post.index') method to generate the URL of this route. And then it will fill in the default value of locale which you have set in your middleware.

Upvotes: 0

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

You need to put the logic into a service provider to make it work instead of using middleware:

public function register()
{
    \URL::defaults(['some_param' => 'some_value']);
}

Then you'll be able to use route('route-name') without passing a required parameter.

Upvotes: 1

FULL STACK DEV
FULL STACK DEV

Reputation: 15941

Lets say you have default param which is used with every request of the application, in that case, you have to use middlewares.

like mentioned in the docs https://laravel.com/docs/5.5/urls#default-values

if you just want to pass default values to routes you can do this.

Route::get('user/{name?}', function ($name = defaultValue) {
   return $name;
});

hope this helps

Upvotes: 0

Related Questions