- Vào dự án frontend chạy lệnh : php artisan make:model Category
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Category extends Model
{
use SoftDeletes;
protected $table = 'categories';
public function categoryChildrent()
{
return $this->hasMany(Category::class, 'parent_id');
}
}
- Vào HomeController.php
<?php
namespace App\Http\Controllers;
use App\Category;
use App\Slider;
use Illuminate\Http\Request;
class HomeController extends Controller
{
public function index()
{
$sliders = Slider::latest()->get();
$categorys = Category::where('parent_id', 0)->latest()->get();
return view('home.home',compact('sliders','categorys'));
}
public function test()
{
return view('test');
}
}
- Vào siderbar.blade.php
<div class="col-sm-3">
<div class="left-sidebar">
<h2>Category</h2>
<div class="panel-group category-products" id="accordian"><!--category-productsr-->
@foreach($categorys as $category)
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordian" href="#sportswear_{{$category->id}}">
<span class="badge pull-right">
@if($category->categoryChildrent->count())
<i class="fa fa-plus"></i>
@endif
</span>
{{$category->name}}
</a>
</h4>
</div>
<div id="sportswear_{{$category->id}}" class="panel-collapse collapse">
<div class="panel-body">
<ul>
@foreach($category->categoryChildrent as $categoryChilrent)
<li><a href="#">{{$categoryChilrent->name}} </a></li>
@endforeach
</ul>
</div>
</div>
</div>
@endforeach
</div><!--/category-products-->
</div>
</div>
- Kết quả :
- Giải thích: kiểm tra nếu có những mục con mới hiện nút +
@if($category->categoryChildrent->count())
<i class="fa fa-plus"></i>
@endif

0 Nhận xét