Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

johncarmackfan95's avatar

Validating uniqueness using a wildcard

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.

0 likes
1 reply
Zyberg's avatar

@johncarmackfan95 Simply create a custom rule (php artisan make:rule UniqueLocally). It will have a method called passes in which you can make a query. The method has params $attribute, $value. For more on that: https://laravel.com/docs/master/validation#using-rule-objects

It is possible to make exceptions on the checks, if you know the id of the resource that you want to exclude by using 'propertyToCheck'=>'unique:table,email_column_to_check,id_to_ignore', but in this case I suggest writing all the logic within the custom rule.

1 like

Please or to participate in this conversation.