Skip to content
Advertisement

Laravel URL Filtering with GET

I am building a simple Laravel routing to display an array when someone goes to http://127.0.0.1:8000/planets

But I need to make a filter to check the array on what request has been send on the URL. For example: http://127.0.0.1:8000/planets?planet=mars

I need to make sure that if a GET parameter is present, you filter the array based on whether the planet name is in it. This way we can filter the results of the page a little faster.

The code I currently have Web.php:

JavaScript

And my welcome blade:

JavaScript

Advertisement

Answer

The Laravel IlluminateHttpRequest object has a query method on it that allows you access to query string parameters.

JavaScript

So for your scenario and given the URL example.com/planets?names=mars,earth, you would grab the planet names as follows:

JavaScript

That would result in the $names variable having the string value mars,earth.

From here you want to use explode to separate out the individual names:

JavaScript

This time $names is an array with two elements, mars and earth.

Then you can use the whereIn method available on Laravel Collections to filter your planets to just those found in the $names array.

JavaScript

Note that for the above to work I have done two things.

  1. I made all the planet names in your $planets array lower case
  2. I use array_map to convert the query parameter values to lower case for comparing with the $planets array

This should mitigate casing issues (so people typing mars, MARS or other variations) should be captured correctly.

Put it all together and you should have something like the following:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement