How to pass an array to Laravel Route parameter - laravel

I wanted to pass a value of typed array to my route parameter, the array could be in any size and a different key-value pairs each time.
Route::get('/example/{array}', ...
So if I have an array like this:
$array = [
'a' => 'one',
'b' => 1,
...
]
I did this but knew already it ain't gonna work because it looks like I'm passing values to my route parameters named a, b, etc.
route('route.name', $array)
As expected the error says:
... [Missing parameter: array]
So I used the serialize().
route('route.name', serialize($array))
I'm still getting an error, something like:
[Missing parameter: s:1:"a";i:1;s:1:"b";i:2;]
What am I missing ? I also don't understand what the last error says.

PHP have for this the http_build_query function.
$array = [
'a' => 'one',
'b' => 1,
];
$query = http_build_query(array('myArray' => $array));
// output: myArray%5Ba%5D=one&myArray%5Bb%5D=1

When passing data to a route in Laravel you should make a practice of passing that data in an array like so:
Route:
Route::get('/example/{array}', ...
Calling the named route:
route('route.name', ['array' => serialize($array)])
I don't know if this formatting is required, but it 1. helps you to better format your routes when passing multiple values, and 2, makes your code more readable.
Laravel Routing Documentation

I found the same problem, and from the tests I did, it seems to be an incompatibility between php and Laravel.
What happens is that php serialize() (and also php json_encode()) use the character «{». This character seems to confuse Laravel router, so the error message.
I have tried to use php htmlspecialchars(serialize($array)) (and other combinations like htmlentities(json_encode($array))) but the problem is that «{» is a normal character so they do not transform it (so continues confusing the Laravel router).
I also tried the solution of Maik Lowrey, but then I do not see an out of the box method to recover the array from the serialized parameter on the other side of the route (urldecode() does nothing).
At last I have used the following ugly turnaround that only works for one-dimension arrays (but works):
In the blade route generation:
['arrayParameter' => trim(json_encode($array), '{}')]
In the Controller function:
$array = json_decode('{' . $arrayParameter . '}', true);
Best regards.

Related

Unable to fetch get parameter with encoded '/' in Laravel using route

I am new to Laravel and working on existing code.
I want to pass some values in url in format of URL/val1/val2/val3.
Every thing is working perfect if all values with normal string or number
but if any value has special character like slash / or \ it shows errors.
eg.
working :- URL/abc/pqr/xys
but if val3 = 22/06 ;url is URL/val1/val2/22/06 error shows 404 not found
If I encoded val3 using javaScript's function encodeURIComponent()
val3=22%2F06 and url become URL/val1/val2/22%2F06 shows Object not found!
// My current route web.php is:-
Route::get('/export/{name}/{status}/{search}', 'ReportController#export')->name('export');
//routes.php
Route::get('view/{slashData?}', 'ExampleController#getData')
->where('slashData', '(.*)');
Your route accept only 3 params. But you pass four params.
Route::get('/export/{name}/{status}/{search}', 'ReportController#export')->name('export');
You must change your val3=22-06. Don't use / as value of your param.
Eg.
URL/val1/val2/22-06
You need to use regex expression for that situation:
Route::get('/export/{name}/{status}/{search}', 'ReportController#export')->name('export')->where(['search' => "[\w\/]+"]);

Reverse construction of Custom Routes from inside a Controller using Pimcore 5.x

As per the Pimcore 5 Documentation:
URLs are generated using the default URL helper of Symfony $this->path() and $this->url(). Additionally to the standard helpers for generating URLs, Pimcore offers a special templating helper ($this->pimcoreUrl()) to generate URLs like you did with Pimcore 4. You can define a placeholder in the reverse pattern with %NAME and it is also possible to define an optional part, to do so just embrace the part with curly brackets { } (see example below).
https://pimcore.com/docs/5.0.x/Development_Documentation/MVC/Routing_and_URLs/Custom_Routes.html
I should be able to reverse construct a route using the path method like so:
$this->path( 'MyRouteName', [
'route_param_a' => 'A',
'route_param_b' => 'B',
'route_param_c' => 'C'
] );
Unfortunately, when I call this from inside a Controller, I get the following error:
Attempted to call an undefined method named "path" of class "AppBundle\Controller\MyController".
Is there a similar function or method available in the Controller scope that I can use to generate my paths when I respond with my JSON object directly from the controller (without using a view)?
Looks like the answer for this is not covered in the Pimcore 5 documentation, rather the Symfony 3 documentation!
https://symfony.com/doc/current/routing.html#generating-urls
$url = $this->generateUrl( 'MyRouteName', [
'route_param_a' => 'A',
'route_param_b' => 'B',
'route_param_c' => 'C'
] );

Laravel pass parameters to route/action

If I want to construct this url: /categories/5/update/?hidden=1 how could I pass both {id} param and hidden param (as GET) ?
My route is:
Route::get('categories/{id}/update', 'CategoryController#update');
I don't want to make a form and put it as POST because I have a number of buttons which simply hides/shows/removes a category and dont want to make a lot of forms for simple actions, although it has nothing to do with the question
I'm just a little bit confused, because it seems like action('CategoryController#update', [$id, 'hidden' => 1]) constructs the right URL but I got no idea how it's distinguished that the first one ($id) must be in URL and the second is a GET param
You may also try this to generate the URL:
$action = action('CategoryController#update', [id => $id]) . '?hidden=1';
Also, query string could be passed with any route even without mentioning about that in Route declaration.

magento _redirect with parameters that have + or /

seems like a call to
$this->_redirect('*/*/myaction',$myargs);
does not properly escape the arguments
so if
$myargs=array(p1=>'string that has + or / within it')
the created URL will be something like:
..../myaction/?p1/string%20that%20has%20+%20or%20/%20within%20it
causing the getParams collection on the action to have
p1 with value 'string that has or ' <- plus sign missing and value broken and
' within it' with no value or something similar.
is there any standard way I should handle the arguments before passing them to _redirect ?
Eyal
Yes, there are two standard ways.
Pass all your params as route params, but encode them with php urlencode() func:
foreach ($myargs as $key => $val) {
$myargs[$key] = urlencode($val);
}
$this->_redirect('*/*/myaction', $myargs);
Pass your params as query params
$this->_redirect('*/*/myaction', array('_query', $myargs));
You'd better take second approach, because your params logically are not route but query parameters. Magento is made with a lot of architecture thinking, so it usually points better ways to do stuff - that's why in your case it's easier to send params using second way.
Notice: _redirect() internally uses Mage_Core_Model_Url, so everything said in this answer is true for all other url-forming routines and all usages of Url model.
refer to http://www.blooberry.com/indexdot/html/topics/urlencoding.htm#whatwhy and read the section "Reserved characters"

Mutliple URL Segments to Index Function With CodeIgniter

Please excuse me if this is an incredibly stupid question, as I'm new to CodeIgniter.
I have a controller for my verification system called Verify. I'd like to be able to use it something like site.com/verify/123/abcd, but I only want to use the index function, so both URL segments need to go to it.
I'm sure this can be done with URL routing somehow, but I can't figure out how to pass both URL segments into Verify's index function..
Something like this in routes.php should do the job:
$route['verify/(:any)/(:any)'] = "verify/index/$1/$2";
I'm pretty sure you can just pass any controller method in CodeIgniter multiple arguments without modifying routes or .htaccess unless I misunderstood the problem.
function index($arg_one, $arg_two)
{
}
$arg_one representing the 123 and $arg_two representing the abcd in your example URI.
You will either need to edit the routes or write an htaccess rule, however i didn't understand why you want to limit to just the index function.
If you didnt wanna use routes for some reason, then you could add this function to the controller in question.
public function _remap($method_in, $params = array()) {
$method = 'process_'.$method_in;
if (method_exists($this, $method)) {
return call_user_func_array(array($this, $method), $params);
}
array_unshift($params, $method_in);
$this->index($params);
}
Basically it does the same as default behavior in CI, except instead of sending a 404 on 'cant find method', it sends unfound method calls to the index.
You would need to alter your index function to take an array as the first argument.
OR if you know that you only ever want 2 arguments, you could change the last 2 lines to
$this->index($method_in, $params[0]);
Of course both solutions fail in someone uses an argument which is the same as a method in your controller.

Resources