R
R
Rustam Idrisov2017-02-28 17:16:10
Laravel
Rustam Idrisov, 2017-02-28 17:16:10

How to display products by categories and subcategories (Laravel 5.4)?

Good afternoon!
I tried to look for the answer to the question myself, but I could not find a more or less complete implementation option.
I'm new to Laravel and have set out to write an online store platform.
Problem:
There is a "Product" model, it stores products.
An online store has categories (of the first level), and they have subcategories (of the second level).
Products can belong to several categories at once (that is, each product can be displayed in several categories).
I do not understand how to do the following:
1) How to correctly implement the creation of categories and subcategories and then associate products with them.
2) How to get the list of products of the requested category or subcategory (ie /category/ or /category/subcategory/) in the future.
3) And how to properly organize routing of this type /shop/{category}/{subcategory}/{productID} (that is, how to write the routing logic correctly).
I would really appreciate someone who can help me figure this out!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jacob1237, 2017-02-28
@RustaMechanic

Your task with categories is not in the context of Laravel - it is a task about storing trees in a DBMS.
I recommend that you read this answer here: https://toster.ru/answer?answer_id=952447#answers_...
The belonging of goods to several categories in relational DBMS (if you work with them) is formalized as a many-to-many relationship (many-to-many).
Routing you have already implemented in your answer. {category} {subcategory} {productID} are the route parameters that will be passed to the controller ( documentation ).
In the controller, you simply pull out these parameters, filter and slip them into the SQL query. Although {category} (as well as subcategory) will even be superfluous here. But for beauty, you can leave.

O
Orbb, 2017-02-28
@humiliation

As written above = many to many
There will be an intermediate table where category ids and one product id will be listed (there are fewer categories than products)
Accordingly, when we go to the category page, we know its id, we get all the product ids from the intermediate table by its id, we get information about goods by their id from the base of goods
???
PROFIT!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question