John Davidson

php - Laravel, only first element of array passed to route is readable

0 comments
Message:


From a blade template I want to pass an array with a variable amount of values to a route, as described in the answer here.


However when I do this I can only ever access the first value in the array I pass to the route.


This is how I call the route in the blade template:


{{ route('stats.downloads', ['stat_kind' => 'files_size', 'group_by' => 'week', 'start' => '2020-11-01', 'end' => '2020-11-10']) }}

this is my route from web.php:


Route::get('stats/downloads', 'StatsController@view_stats_downloads')->name('stats.downloads');

and my controller:


public function view_stats_downloads(Request $request){
// get the input parameters
$group_by = $request->get('group_by');
$stat_kind = $request->get('stat_kind');
$company = $request->get('group_by');
$user = $request->get('user');
$start = $request->get('start');
$end = $request->get('end');

...

The problem is, that I can only ever access the first value of the array I pass to the controller (stat_kind in this case). It doesn't natter in which order I call the get() function either.


What can I do to fix this?


I'm running laravel 5



My Answer:
In Laravel, when you pass an array of values to a route using the `route()` helper function, the values are actually passed as query parameters in the URL. So in your case, the URL generated by `{{ route('stats.downloads', ['stat_kind' => 'files_size', 'group_by' => 'week', 'start' => '2020-11-01', 'end' => '2020-11-10']) }}` will look something like this:

`/stats/downloads?stat_kind=files_size&group_by=week&start=2020-11-01&end=2020-11-10`

To access these values in your controller, you should use the `request()` helper function instead of the `Request` object. Here's how you can modify your controller method:

php
public function view_stats_downloads(){
// get the input parameters
$group_by = request('group_by');
$stat_kind = request('stat_kind');
$company = request('company');
$user = request('user');
$start = request('start');
$end = request('end');

// rest of your code
}


By using the `request()` helper function, you can access all the query parameters passed to the route. This should allow you to access all the values in the array that you passed to the route.

Rate this post

5 of 5 based on 2058 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us