To validate the uniqueness of two columns in Filament PHP, you can create a custom validation rule. Here's an example:
- Create a new validation rule class:
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\DB;
class UniqueTogether implements Rule
{
protected $table;
protected $columns;
public function __construct($table, $columns)
{
$this->table = $table;
$this->columns = $columns;
}
public function passes($attribute, $value)
{
$count = DB::table($this->table)
->where($this->columns[0], $value[0])
->where($this->columns[1], $value[1])
->count();
return $count === 0;
}
public function message()
{
return 'The :attribute has already been taken.';
}
}
- In your resource class, add the validation rule to the fields:
use App\Rules\UniqueTogether;
...
public function fields(Request $request)
{
return [
Forms\Components\Select::make('student_id')
->searchable()
->preload()
->relationship('student','name')
->label(trans_choice('student',1))
->required()
->rules([
new UniqueTogether('your_table_name', ['year_id', 'student_id']),
]),
Forms\Components\Select::make('year_id')
->searchable()
->preload()
->relationship('year','date')
->label(trans_choice('year',1))
->required()
->rules([
new UniqueTogether('your_table_name', ['year_id', 'student_id']),
]),
];
}
Replace your_table_name with the name of your table.
This will validate that the combination of year_id and student_id is unique in the table.