DynamicController.php 2.49 KB
<?php

namespace App\Http\Container\AppSection\Controllers;

use App\Helpers\JsonResource;
use App\Http\Container\AppSection\Requests\DynamicCreateRequest;
use App\Http\Container\AppSection\Requests\DynamicQueryRequest;
use App\Http\Container\AppSection\Requests\DynamicUpdateRequest;
use App\Models\UserDynamic;
use Hikoon\LaravelApi\Support\ApiController;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;

class DynamicController extends ApiController
{
    /**
     * @param \App\Http\Container\AppSection\Requests\DynamicQueryRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(DynamicQueryRequest $request): JsonResponse
    {
        $filter = $request->safe()->except('pageSize');
        $result = UserDynamic::filter($filter)
            ->orderByDesc('is_top')->orderByDesc('created_at')
            ->paginate($request->get('pageSize', 20));

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

    /**
     * @param \App\Http\Container\AppSection\Requests\DynamicCreateRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(DynamicCreateRequest $request): JsonResponse
    {
        $data   = $request->safe()->toArray();
        $result = $request->user()->dynamics()->create($data);
        return JsonResource::success(JsonResource::SUCCESS, $result);
    }

    /**
     * @param \App\Models\UserDynamic $dynamic
     * @return \Illuminate\Http\JsonResponse
     */
    public function show(UserDynamic $dynamic): JsonResponse
    {
        return JsonResource::success(JsonResource::SUCCESS, $dynamic);
    }

    /**
     * @param \App\Http\Container\AppSection\Requests\DynamicUpdateRequest $request
     * @param \App\Models\UserDynamic                                      $dynamic
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(DynamicUpdateRequest $request, UserDynamic $dynamic): JsonResponse
    {
        if ($dynamic->getAttribute('user_id') !== Auth::id()) {
            return JsonResource::fail(JsonResource::NO_PERMISSION);
        }

        $dynamic->update($request->safe()->toArray());
        return JsonResource::success(JsonResource::SUCCESS, $dynamic);
    }

    /**
     * @param \App\Models\UserDynamic $dynamic
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy(UserDynamic $dynamic): JsonResponse
    {
        $dynamic->delete();
        return JsonResource::success(JsonResource::DELETE_SUCCESS);
    }
}