I have checked other threads on array validation but haven't found one talking about my question.
Using Laravel 6, my form presents fields for every active locale, and submits to an updateOrCreate() method in the controller.
I am recieving input from a form like so:
content[en][slug]
content[en][title]
content[fr][slug]
content[fr][title]
The first key in this 2D array is the locale value that could potentially be anything, as it's set from the config file. For every locale specified in config, there will be a slug and other data fields being submited, so it could be more than just 'en' and 'fr'.
These values will be inserted into my model defined like this:
class PageContent extends Model
{
protected $fillable = [
'locale'
,'title'
,'slug'
,'content'
];
}
I need to validate for uniqueness between locale and slug, since there can be the same slug in various languages, but not the same slug within the same language.
I have no idea how to validate this. My DB migration is set up correctly, and won't insert if the attribute pair is not unique, but a SQL Exception is the wrong thing to display to my users.
Here's what I have so far in my request class:
public function rules()
{
return [
'content.*.title' => 'required',
'content.*.slug' => [
'required',
'not_in:admin',
Rule::unique('page_content')->where(
function ( $q ) use ( $locale, $slug ){
return $q->where( 'locale', $locale )
->where( 'slug', $slug )
}
),
],
]
}
I somehow need to set $locale to the value of '*', and $slug to the current slug being validated against.
How should I be approaching this? Also willing to change the structure of my request, if needbe.
Also when updating an entry, it should not check uniqueness against itself.