'How pass '?filter[DBfieldname]=value&[DBfieldname2]=value2' in url in Laravel 8
I need for filtering data based on getting requests,
Current Route
Route::get('datasearch', [Mycontroller::class, 'MyFunction'])->name('this.is.route.name');
Current Forntend form
<form method="get" enctype="multipart/form-data" action="{{ route('this.is.route.name') }}">
@csrf
<select class="form-control" name="searchAdmin">
<option class="hidden" selected disabled>Admin List </option>
<option value="1">Value 1</option>
<option value="2">Value 2</option>
</select>
<<select class="form-control" name="searchAgent">
<option class="hidden" selected disabled>Agent List </option>
<option value="1">Value 1</option>
<option value="2">Value 2</option>
</select>
<input type="submit" value="Search Data" />
</form>
I need to create below type of URL
http://127.0.0.1:8000/datasearch?filter[dbfieldname1]=searchAdmin&filter[dbfieldname2]=searchAgent
Solution 1:[1]
Simply provide an array with key values to the route parameters. For example:
route('products.index', ['manufacturer' => 'Samsung','price' => '10000']);
Solution 2:[2]
If you're not uploading any files, you probably want to use enctype="application/x-www-form-urlencoded" with your forms. The multipart/form-data is to be used with (special) POST requests for which you need file uploads (I'm not sure what happens when you use it with a GET, it might just get ignored).
Then, you have to keep in mind that every name="..." attribute on your inputs/selects/textareas will determine the key of the data in the URL, i.e.
<input type="text" name="username" value="foobar" />
// example.com?username=foobar
// Laravel will interpret it as ['username' => 'foobar']
You can also change this name to username[] to automatically have the inputs parsed as an array (I believe this all works out of the box with PHP, in the end it depends on your server), i.e.
<input type="text" name="username[]" value="foo" />
<input type="text" name="username[]" value="bar" />
// example.com?username[]=foo&username[]=bar
// Laravel will interpret it as ['username' => ['foo', 'bar']]
Lastly, when you put stuff inside the brackets, it will be interpreted as keys inside of that value like so:
<input type="text" name="username[a]" value="foo" />
<input type="text" name="username[b]" value="bar" />
// example.com?username[a]=foo&username[b]=bar
// Laravel will interpret it as ['username' => ['a' => 'foo', 'b' => 'bar']]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bhargav Rangani |
| Solution 2 | Flame |
