F
Filament16mo ago
GDG

Is it possible to make a table column unique on a per tenant basis?

I have implemented multi-tenancy into my application but I want to restrict the name attribute of my Project class to be unique BUT on a tenant by tenant basis. For example: I have $table->string('name')->unique(); which only allows a single, unique name but what I want to do is if Tenant A names it Project1 and then tries to create another called Project1 then that will not be allowed but if Tenant B called one Project1 then this would be fine. Is this possible using any helper or is this going to be a custom function I will need to build? Thanks for your help in advance.
8 Replies
krekas
krekas16mo ago
Custom rule should do it
Brian Kidd
Brian Kidd16mo ago
Yes, agree with @krekas , you create a custom rule or check if the unique rule supports multiple fields. Never done it with the standard unique rule but check the method signature before creating a custom rule.
krekas
krekas16mo ago
unique accepts closure so maybe it could also be done there
MartinKnops
MartinKnops15mo ago
i'm also looking for a sollution, did you manage to fix it?
GDG
GDGOP15mo ago
This is perfect, thanks
GDG
GDGOP15mo ago
Just as an addition to this, I added a cross reference to my pivot table. Just posting here incase anybody had the same issue. There may be a lighter way to do this but wanted to share it all the same.
->rules([
function () {
return function (string $attribute, $value, Closure $fail) {
$hasProject = auth()->user()->projects()
->where('name', $value)
->exists();
if ($hasProject) {
$fail('You already have a project called '.$value);
}
};
},
])
->rules([
function () {
return function (string $attribute, $value, Closure $fail) {
$hasProject = auth()->user()->projects()
->where('name', $value)
->exists();
if ($hasProject) {
$fail('You already have a project called '.$value);
}
};
},
])
krekas
krekas15mo ago
When posting code use three backticks. #✅┊rules 4
Want results from more Discord servers?
Add your server