Browse Source

WIP: division, implement hierarchy

pull/3/head
Muhammad Sulaiman Yusuf 2 years ago
parent
commit
a67feeede1
  1. 30
      app/Http/Controllers/DivisiController.php
  2. 19
      app/Models/Divisi.php

30
app/Http/Controllers/DivisiController.php

@ -7,10 +7,20 @@ use App\Models\Divisi;
class DivisiController extends Controller
{
private function getAllChildren($divisi, $depth = 0, $array = []) {
$array[$divisi->id] = $divisi->name;
foreach($divisi->children as $child){
$array = $this->getAllChildren($child, $depth + 1, $array);
}
return $array;
}
public function add(Request $request){
$this->validate($request, [
'name' => 'required',
'description' => 'required'
'description' => 'string',
'parent' => 'integer'
]);
$data = $request->all();
@ -53,7 +63,6 @@ class DivisiController extends Controller
$delete = $data->delete();
if(!$delete)
return response()->json(['status'=>'failed','message'=> 'Delete failed!','code'=> 500], 500);
@ -64,6 +73,9 @@ class DivisiController extends Controller
{
$payload = $request->all();
if($payload['columns'][0]['value'] == "")
$this->list();
$dataBuilder = $this->setUpPayload($payload, 'm_divisi');
$builder = $dataBuilder['builder'];
$countBuilder = $dataBuilder['count'];
@ -75,12 +87,16 @@ class DivisiController extends Controller
public function list()
{
$data = Divisi::all();
$countData = $data->count();
if(!$data)
$parentMenus = Divisi::whereNull('parent')->with('children')->get();
$divisions = [];
foreach($parentMenus as $menu){
$childs = $this->getAllChildren($menu);
$divisions = $divisions + $childs;
}
$countData = count($divisions);
if($countData == 0)
return response()->json(['status'=>'failed','message'=>'Data not found!','code'=> 404], 404);
return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200);
return response()->json(['status'=>'success','code'=>200,'data'=> $divisions, 'totalRecord'=> $countData], 200);
}
}

19
app/Models/Divisi.php

@ -13,10 +13,29 @@ class Divisi extends Model
protected $fillable = [
'name',
'parent',
'description',
'created_at',
'created_by',
'updated_at',
'updated_by'
];
public static function boot() {
parent::boot();
static::deleting(function($data) {
$data->children()->delete();
});
}
public function parent()
{
return $this->belongsTo('App\Models\Divisi','parent')->where('parent', null)->with('parent');
}
public function children()
{
return $this->hasMany('App\Models\Divisi','parent')->with('children');
}
}

Loading…
Cancel
Save