Last active
August 29, 2015 14:25
-
-
Save t301000/4d6ae4e352f1c13151f7 to your computer and use it in GitHub Desktop.
無窮分類列表 ver 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App; | |
use Illuminate\Database\Eloquent\Model; | |
class Category extends Model | |
{ | |
// 定義 self relation,用來處理子分類 | |
public function childs() | |
{ | |
return $this->hasMany(self::class, 'of_id'); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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') ); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@each('categories.child', $categories, 'category') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment