使用Laravel构建电子商务网站:如何根据产品的ID查看/路由产品


Building an ecommerce site using Laravel: How do I view/route products based on their ID?

我遵循了Tutsplus上关于使用Laravel创建电子商务网站的教程。我现在遇到的问题是尝试路由到子文件夹时。在本教程中,讲师包含了一项功能,您可以在其中按 ID 查看产品。他就是这样做的:

// StoreController.php
public function getView($id) {
    return View::make('store.view')->with('store', Store::find($id));
}

这段代码似乎传递了stores表中的id。我认为当一个产品被点击时,那就是id被传递的时候

// Routes.php
Route::controller('store', 'StoreController');

还有一些模板:

// store'index.blade.php
<h2>Stores</h2>
<hr>
<div id="stores row">
    @foreach($stores as $store)
    <div class="stores col-md-3">
        <a href="/store/products/view/{{ $store->id }}">
            {{ HTML::image($store->image, $store->title, array('class' => 'feature', 'width'=>'240', 'height' => '127')) }}
        </a>
        <h3><a href="/store/products/view/{{ $store->id }}">{{ $store->title }}</a></h3>
        <p>{{ $store->description }}</p>
    </div>
    @endforeach
</div><!-- end product -->

所以。。当我点击一个产品时,它会引导我domain:8000/store/view/6 6在哪里id

这工作正常,但我想知道的是我如何通过子文件夹路由?假设我希望它是这样的:store/view/products/6考虑到我有一个名为 products 的文件夹,我的 view.blade.php 里面是这样的:store/products/view .

在我的StoreController课上,我试图改变这个

public function getView($id) {
    return View::make('store.view')->with('store', Store::find($id));
}

对此

public function getView($id) {
    return View::make('store.product.view')->with('store', Store::find($id));
}

但它似乎不起作用,只给我一个控制器方法找不到错误。

首先,视图名称View::make('store.product.view')与 URL 无关。

您必须更改路线:

Route::controller('store/view', 'StoreController');

然后在控制器中调整方法的名称,因为它应该与 URL 的段相同store/view

public function getProducts($id) {
    return View::make('store.product.view')->with('store', Store::find($id));
}

我强烈建议您阅读有关该主题的Laravel文档