Pass array in Laravel route

Asked

Viewed 681 times

1

I need to pass an array to a controller. I did it as below but it returns the error:

Missing required parameters for [Route: site.add.cart] [URI: adiciona-carrinho/{product}/{option}]. (View: /var/www/html/ecommerce/resources/views/site/pages/product/product.blade.php)

View:

<div class="col-12 offset-lg-6">
    @php
        $array = [1, 2];
    @endphp
    <a id="add-cart" href="{{ route('site.add.cart', ['product' => $product, 'option' => serialize($array)]) }}" class="btn btn-primary mt-5">Adicionar ao Carrinho</a>
</div>

Route:

Route::get('/adiciona-carrinho/{product}/{option}', 'CartController@addCart')->name('site.add.cart');

Controller

public function addCart(Product $product, $option)
{
    dd($option);

}
  • You need to pass the option parameter, without being serialized, and work that information on controller? got it

  • But I need to pass an array on the route. I saw in another question the use of serialize this way. I ended up getting through with json_encode but I wanted to know why serialize does not work.

  • Because of the output format of serialize, now as you’ve managed to pass with js_encode that would be a json , put this as an answer! if your question is not valid, it will not help anyone

1 answer

1

I was able to pass the json_encode() array and then using json_decode() in the controller.

<div class="col-12 offset-lg-6">
    @php
        $array = [1, 2];
    @endphp
    <a id="add-cart" href="{{ route('site.add.cart', ['product' => $product, 'option' => json_encode($array)]) }}" class="btn btn-primary mt-5">Adicionar ao Carrinho</a>
</div>

Route:

Route::get('/adiciona-carrinho/{product}/{option}', 'CartController@addCart')->name('site.add.cart');

Controller:

public function addCart(Product $product, $option)
{
    json_decode($option);
    dd($option);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.