$article = \App\Article::where('slug', $article_slug)->whereHas('category'', function($query){
$query->where('slug', $category_slug);
} use ($category_slug))->firstOrFail();
SEO friendly URLs with category/subcategories/article slug?
Hi,
First of all, I have Article model and articles table in the database. Each article can be shown using Laravel's standard URI structure: www.example.com/articles/5 (where 5 is the article id). Each article has a slug field (slug column in the articles table) , so with Route Model Binding it is easy to change this and have a slug instead of id in the URI:
In RouteServiceProvider.php I just added:
public function boot(Router $router)
{
parent::boot($router);
\Route::bind('articles', function($slug) {
return \App\Article::where('slug', $slug)->firstOrFail();
});
}
... and now I can open articles with: www.example.com/articles/this-is-some-slug .
On the other hand, each article belongs to one category. For example, let's say that there are the following categories:
- Politics
- Sport
- Football
- Tennis
- ATP
- WTA
- Culture
I created these categories by using Baum (an implementation of the Nested Set pattern for Laravel 5's Eloquent ORM). So there is a Category model and categories table in the database:
$table->increments('id');
$table->string('name');
$table->integer('parent_id')->nullable();
$table->integer('lft')->nullable();
$table->integer('rgt')->nullable();
$table->integer('depth')->nullable();
$table->timestamps();
Of course, in articles table there is a column category_id because of One-to-Many relationship (one Article belongs to one Category, one Category can have many Articles).
All articles belonging to some category can be displayed via the following URL: www.example.com/articles/category/1 (where 1 is the category id). If we add slug column to the categories table & set Route Model Binding :
\Route::bind('category', function($slug) {
return \App\Category::where('slug', $slug)->firstOrFail();
});
then we use a slug instead of id: www.example.com/articles/category/politics (this will display all the articles belonging to the category politics).
But I would like to have URIs with the following structure:
-
www.example.com/sport/tennis/wta/article_slug(/category/subcategory/subcategory/article_slug) -
www.example.com/politics/article_slug(/category/article_slug ) and so on... I hope you understand what I want.
The problem is that I have no idea how to do this with Laravel. Is it even possible? How would you solve this problem?
Thanks in advance and sorry for my bad English.
Please or to participate in this conversation.