51
loading...
This website collects cookies to deliver better user experience
Post
and Category
models. We showed the associated category name under each post title on our blog listing page. Now it is time to click that category name and the load all the posts associated with that category i.e. filter posts by that category.web.php
route fileRoute::get('/categories/{category}', function (Category $category) {
return view('posts', [
'posts' => $category->posts
]);
});
category
in this example) must match up. From the callback function we return the posts for that particular category $category->posts
. So, let's add the relation to the Category
model as we did for the Post
model in the previous episode.public function posts() {
return $this->hasMany(Post::class);
}
hasMany()
relation as a category may have many posts.posts()
relation to our category model, let's play with it in the tinker. Boot up tinker php artisan tinker
use App\Models\Category;
$c = Category::first();
$c->posts;
>>> $c->posts;
=> Illuminate\Database\Eloquent\Collection {#4444
all: [
App\Models\Post {#4496
id: 1,
category_id: 1,
title: "Just a personal post",
slug: "just-a-personal-post",
excerpt: "Lorem ipsum is...",
body: "Lorem ipsum is simply a dummy...",
published_at: null,
created_at: "2021-12-15 16:51:59",
updated_at: "2021-12-15 16:51:59",
},
],
}
>>>
>>>
/categories/{{ $post->category->id }}
, we later update it to slug
.<p><a href="/categories/{{ $post->category->id}}">{{ $post->category->title }}</a></p>
id
attribute of the model bound to the route. Let's change it to the slug
attribute by mentioning slug
in the wildcard as {category:slug}
.Route::get('/categories/{category:slug}', function (Category $category) {
return view('posts', [
'posts' => $category->posts
]);
});
slug
instead of id
in the hyperlink.<p><a href="/categories/{{ $post->category->slug}}">{{ $post->category->title }}</a></p>