n31l n31l - 3 months ago 9
PHP Question

Displaying each category on a separate page - laravel

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

Answer

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
Comments