UserQuotationController.php 1.46 KB
<?php

namespace App\Http\Container\AppSection\Controllers;

use App\Helpers\JsonResource;
use App\Http\Container\AppSection\Requests\UserQuotationRequest;
use App\Models\User;
use App\Models\UserQuotation;
use Hikoon\LaravelApi\Support\ApiController;
use Illuminate\Contracts\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;

class UserQuotationController extends ApiController
{
    /**
     * @param \App\Models\User $user
     * @return \Illuminate\Http\JsonResponse
     */
    public function show(User $user): JsonResponse
    {
        $data = $user->singletonQuotation()
            ->when($user->getKey() !== Auth::id(), fn(Builder $builder) => $builder->where('is_public', 1))
            ->first();
        return JsonResource::success(JsonResource::SUCCESS, $data);
    }

    /**
     * @param \App\Http\Container\AppSection\Requests\UserQuotationRequest $request
     * @param \App\Models\User                                             $user
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(UserQuotationRequest $request, User $user): JsonResponse
    {
        if (Auth::id() !== $user->getKey()) {
            return JsonResource::fail(JsonResource::NO_PERMISSION);
        }

        UserQuotation::query()->updateOrCreate(['user_id' => $user->getKey()], $request->safe()->toArray());

        return JsonResource::success(JsonResource::SUCCESS, $user->getAttribute('singletonQuotation'));
    }
}