Azoraqua
2 days ago
143
11
Laravel

Dynamic views (Like products/<slug>) do not work.

Posted 2 days ago by Azoraqua

Hello,

I want to have dynamic product pages (in the format of products/<slug>) that refer to their respective view in products folder.

I've attempted a bit but it doesn't seem to work as it causes a HTTP 404 Error, can someone explain why and perhaps provide a solution?

Routes:

Route::prefix('products')->group(function () {
    Route::get('/', '[email protected]')->name('products');
    Route::get('/{product}', '[email protected]')->where('product', '[a-zA-Z][a-zA-Z0-9]+')->name('products.view');
});

Controller:

public function show(string $slug) {
    if (!View::exists(`products.$slug`)) {
        return abort(404, `Product page '$slug' does not exist.`);
    }

    return view(`products.$slug`, [
        'product' => Product::where('slug', $slug)->firstOrFail()
    ]);
}

Folder structure: https://i.imgur.com/nnf06Pa.png

Please sign in or create an account to participate in this conversation.