Home > database >  Laravel - How do I navigate to a url with a parameter to left of subdirectory
Laravel - How do I navigate to a url with a parameter to left of subdirectory

Time:06-02

I have to test this Route, but I am not sure how to navigate to it.

Route::get('/{type}/Foo/{page}/{date}', 'FooController@index');

I understand that URLs usually have subdirectories defined before the parameters in the URL.

I have worked with URLs like this example

Route::get('/Foo/{type}', 'FooController@index');

which would have an endpoint that looks like

/Foo?type=bar

Does anybody know how to test a route such as the one above?

CodePudding user response:

Well i think that you need to clear out a bit the difference between route and query parameters.

In your case you are trying to use route parameters which will actually look something like:

/{type}/Foo/{page}/{date} => /myType/Foo/15/12-11-2021

Laravel considers the words inside {} as variables that you can retrieve via request so you can do something like:

$request->type 

and laravel will return you the string myType as output.

In your second case that you have tried in the past you are referring to query parameters which are also a part of the $request. Consider it as the "body" of a GET request but i don't mean in any way to convert your post routes to GET :)

The thing with your second url is that:

/Foo/{type} is not similar to /Foo?type=bar

instead it should be like: /Foo/bar

In general query parameters are when you want to send an optional field most of the times in your GET endpoint (for filtering, pagination etc etc) and the route parameters are for mandatory fields that lead to sub-directories for example /Foo/{FooId}/Bar/{BarId}

The thing to remember is that you must be careful about your routes because variables can conflict with other routes.

For example a route looking like this:

Route::get('/foo/{fooId}', [FooController::class, 'getFoo']);
Route::get('/foo/bar', [BarController::class, 'getBar']);

will conflict because laravel will consider bar as the variable of the fooId so your second route can never be accessed.

The solution to this is to order your routes properly like:

Route::get('/foo/bar', [BarController::class, 'getBar']);
Route::get('/foo/{fooId}', [FooController::class, 'getFoo']);

So when you give as a route parameter anything else than bar your will go to your second route and have it working as expected.

  • Related