CountryRegionController.php 1.68 KB
<?php

namespace App\Http\Container\AppSection\Controllers;

use App\Helpers\JsonResource;
use App\Models\CountryRegion;
use App\Support\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Torann\GeoIP\Facades\GeoIP;

class CountryRegionController extends Controller
{
    /**
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request): JsonResponse
    {
        $filter = [
            'parent_id' => $request->get('parent_id', 0),
            'status'    => 1
        ];
        $data   = CountryRegion::filter($filter)
            ->with('children:id,parent_id,identifier,name')
            ->latest('weight')->get(['id', 'name', 'identifier']);

        return JsonResource::success(JsonResource::SUCCESS, $data);
    }

    /**
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function ip(Request $request): JsonResponse
    {
        $result = GeoIP::getLocation($request->get('ip', $request->ip()));
        $data   = [
            'ip'      => $result->getAttribute('ip'),
            'country' => $result->getAttribute('country') ?? '',
            'region'  => $result->getAttribute('state_name') ?? '',
            'city'    => $result->getAttribute('city') ?? ''
        ];

        if (in_array($result->getAttribute('iso_code'), ['HK', 'MO', 'TW'], true)) {
            $data['country'] = '中国';
            $data['region']  = $result->getAttribute('country') ?? '';
            $data['city']    = $result->getAttribute('city') ?? '';
        }

        return JsonResource::success(JsonResource::SUCCESS, $data);
    }
}