To display posts by category in Laravel, you can follow these steps:
1. Define the relationship between the "Category" and "Post" models. In your
Category
model, you could have a method like:
PHP:
public function posts()
{
return $this->hasMany(Post::class);
}
2. In your
Post
model, you could have a method like:
PHP:
public function category()
{
return $this->belongsTo(Category::class);
}
3. In your controller, you can retrieve the posts based on the selected category. For example:
PHP:
use App\Models\Category;
public function postsByCategory($categoryName)
{
$category = Category::where('name', $categoryName)->firstOrFail();
$posts = $category->posts;
return view('posts.index', compact('posts'));
}
4. In your route file (
web.php
), define a route for the posts by category:
PHP:
Route::get('posts/category/{categoryName}', [PostController::class, 'postsByCategory']);
5. Finally, in your
posts/index.blade.php
view, you can iterate over the retrieved posts:
PHP:
@foreach($posts as $post)
<h2>{{ $post->title }}</h2>
<p>{{ $post->content }}</p>
@endforeach
To view posts about IT, for example, you can access the URL:
http://yourdomain.com/posts/category/IT
. Similarly, for accounting, the URL would be:
http://yourdomain.com/posts/category/accounting
.
This approach assumes that you have a "categories" table with a "name" column, and a "posts" table with a "category_id" foreign key column.