Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
26 / 26
100.00% covered (success)
100.00%
5 / 5
CRAP
100.00% covered (success)
100.00%
1 / 1
Create
100.00% covered (success)
100.00%
26 / 26
100.00% covered (success)
100.00%
5 / 5
7
100.00% covered (success)
100.00%
1 / 1
 create
100.00% covered (success)
100.00%
22 / 22
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(HttpStatusCode $code) Returns empty payload error
27 * @method JsonResponse|ResponseInterface answerSuccess(mixed $data, HttpStatusCode $code, array $meta = [])
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        $data = $request->post();
44        $method = $method ?? config('devToolbelt.fast-crud.create.method', 'toArray');
45        $httpStatus = HttpStatusCode::from(
46            config('devToolbelt.fast-crud.create.http_status', HttpStatusCode::CREATED->value)
47        );
48
49        $validationHttpStatus = HttpStatusCode::from(
50            config('devToolbelt.fast-crud.global.validation.http_status', HttpStatusCode::BAD_REQUEST->value)
51        );
52
53        if (empty($data)) {
54            return $this->answerEmptyPayload($validationHttpStatus);
55        }
56
57        $this->beforeCreateFill($data);
58
59        $validationResponse = $this->runValidation($data, $this->createValidateRules());
60
61        if ($validationResponse !== null) {
62            return $validationResponse;
63        }
64
65        $this->beforeCreate($data);
66
67        $modelName = $this->modelClassName();
68        $record = $modelName::query()->create($data);
69
70        $this->afterCreate($record);
71
72        return $this->answerSuccess(
73            data: $record->{$method}(),
74            code: $httpStatus
75        );
76    }
77
78    /**
79     * Hook called before filling the model with request data during creation.
80     *
81     * Override this method to transform, validate, or add additional data
82     * before the model is filled.
83     *
84     * @param array<string, mixed> $data Request data to be filled into the model (passed by reference)
85     */
86    protected function beforeCreateFill(array &$data): void
87    {
88    }
89
90    /**
91     * Hook called before the model is created.
92     *
93     * Override this method for additional validations or
94     * final modifications to the data before persistence.
95     *
96     * @param array<string, mixed> $data The data to be used for creation (passed by reference)
97     */
98    protected function beforeCreate(array &$data): void
99    {
100    }
101
102    /**
103     * Hook called after the model has been successfully created.
104     *
105     * Override this method for post-creation operations like dispatching events,
106     * creating related models, or logging.
107     *
108     * @param Model $record The created model instance
109     */
110    protected function afterCreate(Model $record): void
111    {
112    }
113
114    /**
115     * Define validation rules for the create action.
116     *
117     * Override this method to return Laravel validation rules.
118     * If rules are defined, the data will be validated after beforeCreateFill()
119     * and before beforeCreate().
120     *
121     * @return array<string, mixed> Laravel validation rules
122     *
123     * @example
124     * ```php
125     * protected function createValidateRules(): array
126     * {
127     *     return [
128     *         'name' => ['required', 'string', 'max:255'],
129     *         'email' => ['required', 'email', 'unique:users'],
130     *         'price' => ['required', 'numeric', 'min:0'],
131     *     ];
132     * }
133     * ```
134     */
135    protected function createValidateRules(): array
136    {
137        return [];
138    }
139}