Skip to content

Instantly share code, notes, and snippets.

@t301000
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save t301000/4d6ae4e352f1c13151f7 to your computer and use it in GitHub Desktop.
Save t301000/4d6ae4e352f1c13151f7 to your computer and use it in GitHub Desktop.
無窮分類列表 ver 2
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
// 定義 self relation,用來處理子分類
public function childs()
{
return $this->hasMany(self::class, 'of_id');
}
}
<?php
namespace App\Http\Controllers;
use App\Category;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class CategoryController extends Controller {
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
// 只取得最上層分類,子分類在 view 中處理
$categories = Category::where( 'of_id', 0 )
->get( [ 'id', 'of_id', 'title' ] );
return view( 'categories.index', compact('categories') );
}
}
<div>
{{ str_repeat('----', isset($i) ? $i++ : 0) . $category->title }} <br/>
{{-- 利用 relation 取得子分類,如果有子分類,則逐一遞迴處理 --}}
@if($childs = $category->childs)
@foreach($childs as $category)
@include('categories.child2', ['category' => $category, 'i' => isset($i) ? $i : 1])
@endforeach
@endif
{{-- 子分類 結束 --}}
</div>
@each('categories.child', $categories, 'category')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment