Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
35 / 35
100.00% covered (success)
100.00%
6 / 6
CRAP
100.00% covered (success)
100.00%
1 / 1
Update
100.00% covered (success)
100.00%
35 / 35
100.00% covered (success)
100.00%
6 / 6
11
100.00% covered (success)
100.00%
1 / 1
 update
100.00% covered (success)
100.00%
30 / 30
100.00% covered (success)
100.00%
1 / 1
6
 modifyUpdateQuery
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 beforeUpdateFill
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 beforeUpdate
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 afterUpdate
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 updateValidateRules
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3declare(strict_types=1);
4
5namespace DevToolbelt\LaravelFastCrud\Actions;
6
7use DevToolbelt\Enums\Http\HttpStatusCode;
8use Illuminate\Database\Eloquent\Builder;
9use Illuminate\Database\Eloquent\Model;
10use Illuminate\Http\JsonResponse;
11use Illuminate\Http\Request;
12use Illuminate\Support\Str;
13use Psr\Http\Message\ResponseInterface;
14
15/**
16 * Provides the update (PUT/PATCH/POST by ID) action for CRUD controllers.
17 *
18 * Updates an existing model instance with the request data.
19 *
20 * Lifecycle:
21 * 1. UUID validation (if configured)
22 * 2. beforeUpdateFill() - Transform or add data before validation
23 * 3. updateValidateRules() - Validate data using Laravel validation rules
24 * 4. modifyUpdateQuery() - Customize the query to find the record
25 * 5. beforeUpdate() - Final modifications before persistence
26 * 6. Model::update() - Persist the changes
27 * 7. afterUpdate() - Post-update operations (events, cache, etc.)
28 *
29 * @method string modelClassName() Returns the Eloquent model class name
30 * @method JsonResponse|ResponseInterface answerInvalidUuid(HttpStatusCode $code) Returns invalid UUID error response
31 * @method JsonResponse|ResponseInterface answerEmptyPayload(HttpStatusCode $code) Returns empty payload error response
32 * @method JsonResponse|ResponseInterface answerRecordNotFound(HttpStatusCode $code = HttpStatusCode::NOT_FOUND)
33 *         Returns not found error response
34 * @method JsonResponse|ResponseInterface answerSuccess(mixed $data, HttpStatusCode $code, array $meta = [])
35 *         Returns success response
36 * @method JsonResponse|ResponseInterface|null runValidation(array $data, array $rules)
37 *         Validates data and returns error response if fails, null if passes
38 */
39trait Update
40{
41    /**
42     * Updates an existing record with the request data.
43     *
44     * @param Request $request The HTTP request containing the updated data
45     * @param string $id The identifier value of the record to update
46     * @param string|null $method Model serialization method (default from config or 'toArray')
47     * @return JsonResponse|ResponseInterface JSON response with the updated record or error response
48     */
49    public function update(Request $request, string $id, ?string $method = null): JsonResponse|ResponseInterface
50    {
51        $method = $method ?? config('devToolbelt.fast-crud.update.method', 'toArray');
52        $httpStatus = HttpStatusCode::from(
53            config('devToolbelt.fast-crud.update.http_status', HttpStatusCode::OK->value)
54        );
55
56        $validationHttpStatus = HttpStatusCode::from(
57            config('devToolbelt.fast-crud.global.validation.http_status', HttpStatusCode::BAD_REQUEST->value)
58        );
59
60        $findField = config('devToolbelt.fast-crud.update.find_field')
61            ?? config('devToolbelt.fast-crud.global.find_field', 'id');
62
63        $isUuid = config('devToolbelt.fast-crud.update.find_field_is_uuid')
64            ?? config('devToolbelt.fast-crud.global.find_field_is_uuid', false);
65
66        if ($isUuid && !Str::isUuid($id)) {
67            return $this->answerInvalidUuid($validationHttpStatus);
68        }
69
70        $data = $request->post();
71
72        if (empty($data)) {
73            return $this->answerEmptyPayload($validationHttpStatus);
74        }
75
76        $this->beforeUpdateFill($data);
77
78        $validationResponse = $this->runValidation($data, $this->updateValidateRules());
79
80        if ($validationResponse !== null) {
81            return $validationResponse;
82        }
83
84        $modelName = $this->modelClassName();
85        $query = $modelName::query()->where($findField, $id);
86        $this->modifyUpdateQuery($query);
87
88        /** @var Model|null $record */
89        $record = $query->first();
90
91        if ($record === null) {
92            return $this->answerRecordNotFound();
93        }
94
95        $this->beforeUpdate($record, $data);
96        $record->update($data);
97        $this->afterUpdate($record);
98
99        return $this->answerSuccess(data: $record->{$method}(), code: $httpStatus);
100    }
101
102    /**
103     * Hook to modify the update query before fetching the record.
104     *
105     * Override this method to add eager loading, additional conditions,
106     * or scopes to the query.
107     *
108     * @param Builder $query The query builder instance
109     *
110     * @example
111     * ```php
112     * protected function modifyUpdateQuery(Builder $query): void
113     * {
114     *     $query->where('user_id', auth()->id());
115     * }
116     * ```
117     */
118    protected function modifyUpdateQuery(Builder $query): void
119    {
120    }
121
122    /**
123     * Hook called before filling the model with request data during update.
124     *
125     * Override this method to transform, validate, or add additional data
126     * before the model is filled.
127     *
128     * @param array<string, mixed> $data Request data to be filled into the model (passed by reference)
129     */
130    protected function beforeUpdateFill(array &$data): void
131    {
132    }
133
134    /**
135     * Hook called before the model is updated.
136     *
137     * Override this method for additional validations, setting computed fields,
138     * or any logic that needs access to the record and data before persistence.
139     *
140     * @param Model $record The model instance about to be updated
141     * @param array<string, mixed> $data The data to be used for update (passed by reference)
142     */
143    protected function beforeUpdate(Model $record, array &$data): void
144    {
145    }
146
147    /**
148     * Hook called after the model has been successfully updated.
149     *
150     * Override this method for post-update operations like dispatching events,
151     * updating related models, or logging.
152     *
153     * @param Model $record The updated model instance
154     */
155    protected function afterUpdate(Model $record): void
156    {
157    }
158
159    /**
160     * Define validation rules for the update action.
161     *
162     * Override this method to return Laravel validation rules.
163     * If rules are defined, the data will be validated after beforeUpdateFill()
164     * and before finding the record.
165     *
166     * For partial updates, use the 'sometimes' rule to only validate fields that are present.
167     *
168     * @return array<string, mixed> Laravel validation rules
169     *
170     * @example
171     * ```php
172     * protected function updateValidateRules(): array
173     * {
174     *     return [
175     *         'name' => ['sometimes', 'string', 'max:255'],
176     *         'email' => ['sometimes', 'email', 'unique:users,email,' . request()->route('id')],
177     *         'price' => ['sometimes', 'numeric', 'min:0'],
178     *     ];
179     * }
180     * ```
181     */
182    protected function updateValidateRules(): array
183    {
184        return [];
185    }
186}