Showing Category And Subcategory In Laravel -
i using laravel 5.2. have 2 eloquent models this-
category.php-
<?php namespace app; use illuminate\database\eloquent\model; class category extends model { protected $table = 'categories'; //table name public $timestamps = false; public $incrementing = false; //for non integer primary key protected $primarykey = 'name'; protected $fillable = [ 'name' ]; public function subcategory() { return $this->hasmany('app\subcategory', 'category_id', 'id'); } }
and subcategory.php-
<?php namespace app; use illuminate\database\eloquent\model; class subcategory extends model { protected $table = 'sub_categories'; //table name public $timestamps = false; protected $fillable = [ 'category_id', 'name' ]; }
so, if call in controller-
return category::with('subcategory')->get();
i getting this-
[ { "id": 3, "name": "beahan-mueller", "sub_category": [ { "id": 27, "category_id": 3, "name": "carroll trail" }, { "id": 3, "category_id": 3, "name": "davis lake" }, { "id": 9, "category_id": 3, "name": "lehner ranch" } ] }, { "id": 10, "name": "beahan, stark , mckenzi", "sub_category": [ { "id": 1, "category_id": 10, "name": "dibbert summit" }, { "id": 18, "category_id": 10, "name": "kris mount" } ] } ]
so, can tell sub-category link working, right?
but problem if want use blade show values this-
controller-
return view('public.listing.main', [ 'current_page' => 'add listing', 'categories' => category::with('subcategory')->get() ]);
view-
@foreach ($categories $category) <li class="no-border"> <label class="pull-left"> <input type="checkbox" name="cat_{{ $category->id }}" checked> <strong> {{ $category->name }} (21)</strong> </label> <ul> @foreach($category->sub_category $sub_cat) <li> <label class="pull-left"> <input type="checkbox" checked value="{{ $sub_cat->id }}"> {{ $sub_cat->name }} (7) </label> </li> @endforeach </ul> </li> @endforeach
i finding error it-
can please help, why finding error?
your subcategory relationship name wrong in 2nd foreach. should
@foreach($category->subcategory $sub_cat) // code here @endforeach
instead of sub_category
.
Comments
Post a Comment