How to get an array from GET URL parameters in Laravel

Viewed 2432

Hello to everyone who is seeing this! I am a Laravel beginner, using Laravel for API-s calls. I cannot find an appropriate solution how to pick up parameters from GET method that looks like this:

http://localhost:8000/api/products/searchv2/cat=category1&cat=category2

Now I want to receive in my Laravel controller this array

$categories = ["category1", "category2"]

I think the solution is very easy, but due to minimal experience, I cannot find the right answer on the internet or Laravel documentation. Thanks to everyone who tried to help me!

1 Answers

According to this answer, you can use the [] syntax like you would with form fields to create an array. So in your case, the URL would be:

http://localhost:8000/api/products/searchv2/?cat[]=category1&cat[]=category2

And $_GET['cat'] should return an array, so in theory $request->get('cat') would also return an array.

Using Commas

Another way would be to make use of commas, e.g.:

?cat=category1,category2,category3

You could then use explode:

$categories = explode($request->get('cat'));
Related