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