n31l n31l - 1 month ago 5x
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.


public function show($id)
$post->withCategories($Categories)->$id->($id as **javascript)**

( corresponding view )

@foreach ($categories as $category->$id>**javascript**)
<th>{{ $category->id }}</th>
<td>{{ $category->name }}</td>
</div> <!-- end of .col


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');

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>