0

My Route

Route::get('complete/{purchase_id}/{failed_purchases?}', 'Controller@success');

My Controller

$failed_purchases = [];
for($i=0 ; $i < 2; $i++){
    $failed_purchases[] = [
        'reason' => "failed $i"
    ];
}


return redirect()->route('customer.purchase.success-purchase', [
    'purchase_id' => 10,
    'failed_purchases' => json_encode($failed_purchases)
]);

I need to pass an array with the route, when i try this code but i got an error Missing required parameters for [Route.

I also tried serialize(). How to solve this ?

Yves Kipondo
  • 5,289
  • 1
  • 18
  • 31
JIJOMON K.A
  • 1,290
  • 3
  • 12
  • 29

3 Answers3

0

I am not sure about better solution. but hope this will solve your problem.

route will be ->

Route::get('complete/{purchase_id}', 'Controller@success');
// it will pass the array as a querystring. and then you can get from request input.

controller will be ->

function success(Request $request, $purchase_id) {
    // do your stuff
    $failed_purchases = $request->input('failed_purchases');
}
hasan05
  • 904
  • 5
  • 22
0

I supposed you want to interpolet the value of $i in the string "failed $i" you must wrap the name of the variable in curly brace like bellow

$failed_purchases = [];
for($i=0 ; $i < 2; $i++){
    $failed_purchases[] = [
        'reason' => "failed {$i}"
    ];
}

And after the loop the value of $failed_purchases I presume will be equal to

$failed_purchases = [
    [
        "reason" => "failed 0"
    ],
    [
        "reason" => "failed 1"
    ],
]

and after you use json_encode passing the value of $failed_purchases it will return a string equal to

[{"reason":"failed 0"},{"reason":"failed 1"}]

which have many double quote in it and to use that value as part in your URL you must escape it using function like urlencode

$failed_purchases_string = json_encode($failed_purchases);
$failed_purchases_string_encode = urlencode($failed_purchases_string);

which will be equal to some thing like this

%5B%7B%22reason%22%3A%22failed+0%22%7D%2C%7B%22reason%22%3A%22failed+1%22%7D%5D

And at this step it can be use as parameter into the route method There is one limitation which is the maximum length of a URL which mustn't exceed 2048 characters

Yves Kipondo
  • 5,289
  • 1
  • 18
  • 31
0

Everything looks good except one thing. Just make sure you have provided failed_purchases parameter with some default value in Controller because you have specified this parameter as optional. So your Controller action should be something like:

function success(Request $request, $purchase_id, $failed_purchases=null){
    //Your Code
}
Plutian
  • 2,276
  • 3
  • 14
  • 23