Laravel - displaying categories by id

倖福魔咒の 提交于 2019-12-13 21:39:17

问题


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

回答1:


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>


来源:https://stackoverflow.com/questions/39222584/laravel-displaying-categories-by-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!