Database 通过foreach循环动态返回视图
我有一个由数据库运行的foreach循环:Database 通过foreach循环动态返回视图,database,laravel,dynamic,foreach,controller,Database,Laravel,Dynamic,Foreach,Controller,我有一个由数据库运行的foreach循环: <div id="nav" > @foreach(\App\Categories::whereNull('parent_id')->get() as $category) <a id="link1" href="{{ route('showCategory' , $category->id) }}" ><div class="link">{{ $category->name }}<
<div id="nav" >
@foreach(\App\Categories::whereNull('parent_id')->get() as $category)
<a id="link1" href="{{ route('showCategory' , $category->id) }}" ><div class="link">{{ $category->name }}</div></a>
@endforeach
</div>
我的控制器:
public function showCategory(Categories $category) {
}
public function myFunction()
{
$categories = Categories::all()->take(5)->get();
return view('your.view')->with('categories', $categories);
}
我猜您希望为每个类别创建一个链接,该链接指向一个页面,该页面显示有关所选类别的更多信息 您在其中为所有类别创建链接的刀片文件对我来说似乎很好,但我建议将您的路由文件更改为: 路由::获取'/category/{id}','PagesController@showCategory“->命名为“showCategory” 然后,对于showCategory函数,您需要以下内容:
public function showCategory($id) {
$category = Categories::find($id);
// i used categories.show here, change it to whatever view you use
return view('categories.show')->with('category', $category);
}
然后在categories.show视图中,您可以访问该类别的属性,如下所示:
$category->id;//或者任何你想展示的东西
根据OP的要求:数据库中指向其页面的前5个类别:
在控制器中:
public function showCategory(Categories $category) {
}
public function myFunction()
{
$categories = Categories::all()->take(5)->get();
return view('your.view')->with('categories', $categories);
}
在刀片视图中,假设类别的视图位于:/category/id:
谢谢你的回答。如果我有5个不同的链接,每个链接都有一个不同的“href”,你会建议如何在类别中这样做。显示?在一个类别中显示5个不同的链接?或者5个不同的类别指向他们的页面?5个不同的类别指向他们的页面就是我的意思。你想从你的数据库中随机抽取5个类别吗?都是吗?或是前5名或后5名,前5名。