I am using laravel 5.1 for my project. My issue was to dispaly the data as per category_id which foreign key of table category. This code only get DATA having category_id 1 and this loop only run at $i=1 and after that they can not be iterate. Please help me to solve out this issue.
My controller code was:-
public function category()
{
$category2=Category::all();
for($i=1;$i<=count($category2);$i++)
{
$category=HelpCenter::where('category_id','=',$i)->get();
return view('folder/category',compact('category'));
}
}
My view code was:-
@foreach($category as $category)
<li><a href="/category/{{$category->id}}"> {{$category->questions}}</a></li>
@endforeach
You cannot use the same variable for iterating as the array you are iterating ($category as $category
). You MUST be getting some kind of error because of that.
That being said, you cannot return multiple views with a controller. You will just return the first result that you get.
What you should be doing is something like this:
public function category()
{
$category2=Category::all();
$categories = [];
for($i=1;$i<=count($category2);$i++)
{
$categories[]=HelpCenter::where('category_id','=',$i)->get();
}
return view('folder/category',compact('categories'));
}
And then in your view:
@foreach($categories as $category)
<li><a href="/category/{{$category->id}}"> {{$category->questions}}</a></li>
@endforeach
You are returning from the loop when it runs for one category. Just place your return line after closing loop braces. Like this..
public function category()
{
$category2=Category::all();
for($i=1;$i<=count($category2);$i++)
{
$category[]=HelpCenter::where('category_id','=',$i)->get();
}
return view('folder/category',compact('category'));
}
Hope this will solve your problem.
It is good to use relationship between Category
and HelpCenter
. For more info Check Here
But if you want to do this way then I think this is better way :
public function category()
{
$category2=Category::all();
$category = [];
foreach($category2 as $cat ){
$category[] = HelpCenter::where('category_id','=',$cat->id)->get();
}
return view('folder/category',compact('category'));
}