diff --git a/app/Http/Controllers/Admin/LocationsController.php b/app/Http/Controllers/Admin/LocationsController.php index d74f05d1..4f6343e5 100644 --- a/app/Http/Controllers/Admin/LocationsController.php +++ b/app/Http/Controllers/Admin/LocationsController.php @@ -43,35 +43,21 @@ class LocationsController extends Controller public function getIndex(Request $request) { return view('admin.locations.index', [ - 'locations' => Models\Location::select( - 'locations.*', - DB::raw('(SELECT COUNT(*) FROM nodes WHERE nodes.location_id = locations.id) as a_nodeCount'), - DB::raw('(SELECT COUNT(*) FROM servers WHERE servers.node_id IN (SELECT nodes.id FROM nodes WHERE nodes.location_id = locations.id)) as a_serverCount') - )->paginate(20), + 'locations' => Models\Location::withCount('nodes', 'servers')->paginate(20), ]); } public function deleteLocation(Request $request, $id) { - $model = Models\Location::select( - 'locations.id', - DB::raw('(SELECT COUNT(*) FROM nodes WHERE nodes.location_id = locations.id) as a_nodeCount'), - DB::raw('(SELECT COUNT(*) FROM servers WHERE servers.node_id IN (SELECT nodes.id FROM nodes WHERE nodes.location_id = locations.id)) as a_serverCount') - )->where('id', $id)->first(); + $location = Models\Location::withCount('nodes')->findOrFail($id); - if (! $model) { + if ($location->nodes_count > 0) { return response()->json([ - 'error' => 'No location with that ID exists on the system.', - ], 404); - } - - if ($model->a_nodeCount > 0 || $model->a_serverCount > 0) { - return response()->json([ - 'error' => 'You cannot remove a location that is currently assigned to a node or server.', + 'error' => 'You cannot remove a location that is currently assigned to a node.', ], 422); } - $model->delete(); + $location->delete(); return response('', 204); } diff --git a/app/Models/Location.php b/app/Models/Location.php index 5c8feb9f..f9ceec76 100644 --- a/app/Models/Location.php +++ b/app/Models/Location.php @@ -41,4 +41,24 @@ class Location extends Model * @var array */ protected $guarded = ['id', 'created_at', 'updated_at']; + + /** + * Gets the nodes in a specificed location. + * + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function nodes() + { + return $this->hasMany(Node::class); + } + + /** + * Gets the servers within a given location. + * + * @return \Illuminate\Database\Eloquent\Relations\HasManyThrough + */ + public function servers() + { + return $this->hasManyThrough(Server::class, Node::class); + } } diff --git a/resources/views/admin/locations/index.blade.php b/resources/views/admin/locations/index.blade.php index 9aaf49fa..2fbd4b05 100644 --- a/resources/views/admin/locations/index.blade.php +++ b/resources/views/admin/locations/index.blade.php @@ -46,8 +46,8 @@
{{ $location->short }}