简体   繁体   中英

Laravel 5.3 passing parameter from view to controller

I am making an online shop, so it has products. I am outputing all the products images and their names and I want when the user clicks on the product to redirect him to a single-product page the problem I have is passing the id of the product to the single-product view.

Here's my code Routing:

Route::get('single', [
    "uses" => 'ProductsController@single',
    "as" => 'single'
]);

Index.blade.php:

<a href="{{ route('single', $product->product_id) }}" class="link-product-add-cart">See product</a>

And the controller:

public function single($product_id)
{
    $product = Product::where('product_id', $product_id);

    return view('single-product', compact("product"));
}

Make changes to your route as given below:

Route::get('single/{product_id}', [
    "uses" => 'ProductsController@single',
    "as" => 'single'
]);

If you want to pass any parameters to your route then you've to assign placeholders for the parameters, so in your case, the {product_id} will be used as the placeholder which will be used to take the parameter from the URI , for example: http://example.com/single/1 . So, you'll receive the 1 as $product_id in your single method.

You need to capture segments of the URI within your route .

Route::get('single/{id}', [
    "uses" => 'ProductsController@single',
    "as" => 'single'
]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM