What's with the json decode/encode dance. You just need the PHP collection to iterate in your view.
By the way, this is a good example of when to use a View composer rather than doing a database query in your view.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I'm trying to get all main categories in the header of site but only one category is showing, here is link of pic of admin panel where records are coming from db:
https://imageshack.com/i/plRp0Inbp
and here is link of pic of index page where only 1 category is showing:
https://imageshack.com/i/plIIRDDBpcan anyone provide the solution for this?
Here is ProductsController:
public function products($url = null)
{
$categories = Category::with('products')->where(['parent_id'=>0])->get();
$categoryDetails = Category::where(['url' => $url])->first();
if($categoryDetails->parent_id==0)
{
//if url is main category url
$subCategories = Category::where(['parent_id'=>$categoryDetails])->get();
$cat_ids = "";
foreach ($subCategories as $subCat) {
$cat_ids .= $subCat->id.",";
}
$productsAll = Product::whereIn('category_id',array($cat_ids))->get();
}
else
{
//if url is sub category url
$productsAll = Product::where(['category_id' => $categoryDetails->id])
->get();
}
return view('products.listing')
->with(compact('categories','categoryDetails','productsAll'));
}
and on the listing.blade.php I write this to relate it with categories:
{{ $categoryDetails->name }}
Code of Controller: (default Controller.php)
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use App\Category;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
public static function mainCategories(){
$mainCategories = Category::where(['parent_id' => 0])->get();
//$mainCategories = json_decode(json_encode($mainCategories));
/*echo "<pre>"; print_r($mainCategories); die;*/
return $mainCategories;
}
}
The code I write in the header view:
header.blade.php
<?php use App\Http\Controllers\Controller;
$mainCategories = Controller::mainCategories();
?>
<!--some html-->
@foreach($mainCategories as $cat)
<div class="dropdown-content">
<a href="{{ asset('products/'.$cat->url) }}" style="margin-bottom: -10px;">{{ $cat-
>name }}</a>
</div>
@endforeach
Probably you need to put the menu items inside the foreach, not the whole menu. My guess is that the three items are rendered on top of each other
try
<div class="dropdown-menu">
@foreach($mainCategories as $cat)
<a class="dropdown-item" href="{{ asset('products/'.$cat->url) }}">{{ $cat->name }}</a>
@endforeach
</div>
Please or to participate in this conversation.