diff --git a/app/Http/Controllers/DivisiController.php b/app/Http/Controllers/DivisiController.php index aa265d8..06a533c 100644 --- a/app/Http/Controllers/DivisiController.php +++ b/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); } } diff --git a/app/Models/Divisi.php b/app/Models/Divisi.php index 9b0dea1..5a37c85 100644 --- a/app/Models/Divisi.php +++ b/app/Models/Divisi.php @@ -12,11 +12,30 @@ class Divisi extends Model const UPDATED_AT = 'updated_at'; protected $fillable = [ - 'name', - 'description', - 'created_at', - 'created_by', - 'updated_at', + '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'); + } }