【问题标题】:Laravel 5.3 passing parameter from view to controllerLaravel 5.3 将参数从视图传递到控制器
【发布时间】:2016-11-07 18:39:10
【问题描述】:

我正在做一个网上商店,所以它有产品。我正在输出所有产品图像及其名称,我希望当用户单击产品以将他重定向到单个产品页面时,我遇到的问题是将产品的 id 传递给单个产品视图。

这是我的代码路由:

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>

和控制器:

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

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

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    您需要在 route 中捕获 URI 的片段。

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

    【讨论】:

    • 我得到缺少 [Route: single] [URI: single/{id}] 的必需参数。错误
    • 在您的视图中传递参数,如下所示:{{ route('single', ['id' =&gt; $product-&gt;product_id]) }}
    • 有关在路由 URL 中传递参数的更多信息,请访问此链接:laravel.com/docs/5.3/helpers#method-route
    • 我继续遇到同样的错误:&lt;a href="{{ route('single', ['product_id' =&gt; $product-&gt;product_id]) }}" class="link-product-add-cart"&gt;See product&lt;/a&gt;
    • 将路由id重命名为product_id Route::get('single/{product_id}'...
    【解决方案2】:

    如下所示更改您的路线:

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

    如果您想将任何参数传递给您的路由,那么您必须为参数分配占位符,因此在您的情况下,{product_id} 将用作占位符,用于从 @ 获取参数987654323@,例如:http://example.com/single/1。因此,您将在单一方法中以 $product_id 的形式收到 1

    【讨论】:

    • 我得到缺少 [Route: single] [URI: single/{id}] 的必需参数。错误
    • 是否有可用的product_id 归档或产品表中的其他内容?
    • 我有表 products,唯一的 id 键名为 product_id
    猜你喜欢
    • 1970-01-01
    • 2016-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多