Reputation: 93
For a blog site, I have all the posts & lists of categories displaying on a page though now I need to display the posts for each category on it's own separate page.
Let's say I had a category that was 'Javascript' and I wanted only the posts with the category of javascript displayed on a page.
What's the correct code to do this? here's an example of what I have at the moment.
categoriesController.php
public function show($id)
{
$post->withCategories($Categories)->$id->($id as **javascript)**
}
javascript.blade.php
( corresponding view )
<tbody>
@foreach ($categories as $category->$id>**javascript**)
<tr>
<th>{{ $category->id }}</th>
<td>{{ $category->name }}</td>
</tr>
@endforeach
</tbody>
</table>
</div> <!-- end of .col
Upvotes: 0
Views: 666
Reputation: 5876
If you have set up the relations in the laravel models properly you could use whereHas:
$posts = Post::whereHas('categories', function ($query) {
$query->where('name', '=', 'javascript');
})->get();
However I would personally flip the order and load the Category
first so you query it by name:
$category = Category::with('posts')->where('name', '=', 'javascript')->get();
And then in the view:
{{ $category->name }}<br>
@foreach(category->posts as $post)
{{ $post->title }}<br>
@endforeach
Upvotes: 1