Description
I'm still new to Laravel JSON API. I had a
<?
class UpsellRequest extends ResourceRequest
{
/**
* Get the validation rules for the resource.
*
* @return array
*/
public function rules(): array
{
return [
"salesarea" => JsonApiRule::toOne(),
"upsell_variant" => ["required", "string"],
"name" => ["required", "string"],
];
}
}
The accompanying schema is as follows
<?
class UpsellSchema extends Schema {
/* ... */
public function fields(): array
{
return [
ID::make(),
Str::make("name"),
Str::make("upsell_variant"),
BelongsTo::make("salesarea"),
HasMany::make("upsell-products"),
DateTime::make("createdAt")
->sortable()
->readOnly(),
DateTime::make("updatedAt")
->sortable()
->readOnly(),
];
}
}
I tried creating a new Upsell with a salesarea relation, and sent the following data
{
"data": {
"type": "upsells",
"attributes": {
"name": "Test",
"upsell_variant": "upsell"
},
"relationships": {
"salesarea": {
"data": {
"type": "salesareas",
"id": "1"
}
}
}
}
}
The resource is created succesfully (200 OK), the Upsell model with name Test
is created, all looks ok!
After inspecting the created model, I found that the salesarea_id
is set to 0
.
After a lot of searching in
- The upsell schema
- The salesarea schema
- The relationships in the route
- The upsell and salesarea policies
- The data I'm sending on the frontend
I figured out that the issue lied with the Request, I had named rule salesareas
(referring to the resource name: "salesareas"
) and not salesarea
(referring to the field in the schema).
I'm noticing that in general it's very difficult to know which naming convention to use when, and I really hope it could be included in the base library to throw errors as early as possible to prevent having to search through all the related logic for a tiny singular typo or confusion between a schema field and relation.