简体   繁体   English

Laravel 5.3将参数从视图传递到控制器

[英]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. 我正在输出所有产品图像及其名称,当用户单击产品以将其重定向到单个产品页面时,我想要将产品ID传递到单个产品视图的问题是我想要的。

Here's my code Routing: 这是我的代码路由:

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

Index.blade.php: 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 . 如果要将任何参数传递给路由,则必须为参数分配占位符,因此,在这种情况下, {product_id}将用作占位符,用于从URI中获取参数,例如: http://example.com/single/1 : http://example.com/single/1 So, you'll receive the 1 as $product_id in your single method. 因此,您将在单个方法中收到1作为$product_id

You need to capture segments of the URI within your route . 您需要捕获路由中的URI段。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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