Search code examples
phplaravellaravel-8laravel-routinglaravel-9

How to use array as route parameter properly


I have a form with this action:

<form method="POST" action="{{ route('products.create.post.attribute',['product'=>$product->id,'total'=>$total_counts,'array'=>$attribute_ids]) }}">

So basically, $attribute_ids is an array like this:

array:6 [▼
  0 => 14
  1 => 15
  2 => 16
  3 => 3
  4 => 7
  5 => 8
]

And here is the route:

Route::post('/create/product/addAttribute/{product}/{total}/{array}', [ProductController::class, 'postAttribute'])->name('products.create.post.attribute');

Then at the Controller, I set up the method like this:

public function postAttribute(Request $request, Product $product, $total,$array){

But I get this error:

Too few arguments to function ProductController::postAttribute(), 3 passed in C:\projectname\vendor\laravel\framework\src\Illuminate\Routing\Controller.php on line 54 and exactly 4 expected

So what's going wrong here? How can I properly use array as route parameter?


Solution

  • The error occurs because you using array as parameter name. Change the parameter name and it should work.

    blade

    <form method="POST" action="{{ route('products.create.post.attribute',['product'=>$product->id,'total'=>$total_counts,'myarray'=>$attribute_ids]) }}">
    

    route

    Route::post('/create/product/addAttribute/{product}/{total}/{myarray}', [ProductController::class, 'postAttribute'])->name('products.create.post.attribute');
    

    controller

    public function postAttribute(Request $request, Product $product, $total, $myarray){