Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
5 / 5
CRAP
100.00% covered (success)
100.00%
1 / 1
Create
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
5 / 5
7
100.00% covered (success)
100.00%
1 / 1
 create
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
3
 beforeCreateFill
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 beforeCreate
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 afterCreate
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 createValidateRules
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\Model;
9use Illuminate\Http\JsonResponse;
10use Illuminate\Http\Request;
11use Psr\Http\Message\ResponseInterface;
12
13/**
14 * Provides the creation (POST) action for CRUD controllers.
15 *
16 * Creates a new model instance from the request data and persists it to the database.
17 *
18 * Lifecycle:
19 * 1. beforeCreateFill() - Transform or add data before validation
20 * 2. createValidateRules() - Validate data using Laravel validation rules
21 * 3. beforeCreate() - Final modifications before persistence
22 * 4. Model::create() - Persist the record
23 * 5. afterCreate() - Post-creation operations (events, cache, etc.)
24 *
25 * @method string modelClassName() Returns the Eloquent model class name
26 * @method JsonResponse|ResponseInterface answerEmptyPayload() Returns empty payload error
27 * @method JsonResponse|ResponseInterface answerSuccess(array $data, array $meta, HttpStatusCode $code)
28 *         Returns success response
29 * @method JsonResponse|ResponseInterface|null runValidation(array $data, array $rules)
30 *         Validates data and returns error response if fails, null if passes
31 */
32trait Create
33{
34    /**
35     * Creates a new record from the request data.
36     *
37     * @param Request $request The HTTP request containing the model data
38     * @param string|null $method Model serialization method (default from config or 'toArray')
39     * @return JsonResponse|ResponseInterface JSON response with 201 Created on success, or error response
40     */
41    public function create(Request $request, ?string $method = null): JsonResponse|ResponseInterface
42    {
43        $method = $method ?? config('devToolbelt.fast-crud.create.method', 'toArray');
44        $data = $request->post();
45
46        if (empty($data)) {
47            return $this->answerEmptyPayload();
48        }
49
50        $this->beforeCreateFill($data);
51
52        $validationResponse = $this->runValidation($data, $this->createValidateRules());
53
54        if ($validationResponse !== null) {
55            return $validationResponse;
56        }
57
58        $this->beforeCreate($data);
59
60        $modelName = $this->modelClassName();
61        $record = $modelName::query()->create($data);
62
63        $this->afterCreate($record);
64
65        return $this->answerSuccess(
66            data: $record->{$method}(),
67            code: HttpStatusCode::CREATED
68        );
69    }
70
71    /**
72     * Hook called before filling the model with request data during creation.
73     *
74     * Override this method to transform, validate, or add additional data
75     * before the model is filled.
76     *
77     * @param array<string, mixed> $data Request data to be filled into the model (passed by reference)
78     */
79    protected function beforeCreateFill(array &$data): void
80    {
81    }
82
83    /**
84     * Hook called before the model is created.
85     *
86     * Override this method for additional validations or
87     * final modifications to the data before persistence.
88     *
89     * @param array<string, mixed> $data The data to be used for creation (passed by reference)
90     */
91    protected function beforeCreate(array &$data): void
92    {
93    }
94
95    /**
96     * Hook called after the model has been successfully created.
97     *
98     * Override this method for post-creation operations like dispatching events,
99     * creating related models, or logging.
100     *
101     * @param Model $record The created model instance
102     */
103    protected function afterCreate(Model $record): void
104    {
105    }
106
107    /**
108     * Define validation rules for the create action.
109     *
110     * Override this method to return Laravel validation rules.
111     * If rules are defined, the data will be validated after beforeCreateFill()
112     * and before beforeCreate().
113     *
114     * @return array<string, mixed> Laravel validation rules
115     *
116     * @example
117     * ```php
118     * protected function createValidateRules(): array
119     * {
120     *     return [
121     *         'name' => ['required', 'string', 'max:255'],
122     *         'email' => ['required', 'email', 'unique:users'],
123     *         'price' => ['required', 'numeric', 'min:0'],
124     *     ];
125     * }
126     * ```
127     */
128    protected function createValidateRules(): array
129    {
130        return [];
131    }
132}