n31l
n31l

Reputation: 93

Laravel - displaying categories by id

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 categorie 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, the bold 'javascript' is what needs to be replaced with the correct code.

-- 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: 2163

Answers (1)

Illia Yaremchuk
Illia Yaremchuk

Reputation: 2025

For example: post.php model class Post extends Model { protected $primaryKey = 'id';

    function withCategories() {
       return $this->hasOne('App\Categories', 'id', 'category_id');
    }

    public function show($id){
         Post::with('withCategories')->where('category_id', $id)->get(); //the output of articles of the category
    }
}

$id is a parameter of url: site.com/posts/javascript

in posts.blade.php

<table>
<tbody>
@foreach ($posts as $post)
<tr>
<th>{{ $post->id }}</th>
<td>{{ $post->name }}</td>
<td>{{ $post->withCategories->name }}</td> <!-- Category name-->
</tr>
@endforeach
</tbody>
</table>
</div>

Upvotes: 1

Related Questions