Home > Enterprise >  how to prevent dublicate data with validation in laravel livewire
how to prevent dublicate data with validation in laravel livewire

Time:10-24

I want to prevent data dublication in db so need to use validation.If the same classroom was used before there should be an error message "this classroom already exists". How to create a custom validation like this in laravel?

here's my current code:

<div class="sm:col-start-1 sm:col-end-3 col-span-3  ">
    <x-select x-on:change="isShowing = $event.target.value" name="classroom_id" label="{!! __('Sınıf') !!}" wire:model="classroom_id"
            id="classroom_id"
            :options="$this->classes"/>
    <x-jet-input-error for="classroom_id" hljs-number">2" />
</div>

<div hljs-number">2 " x-show="isShowing">
    <label hljs-string">" for="course_name">
        {{ __('Ders') }}
    </label>
    <input wire:model.debounce.250ms="course_name" type="text" name="course_name" id="course_name" hljs-string">" />
    <x-jet-input-error for="course_name" hljs-number">2" />
</div>
public function saveCourse(){
    $this->validate(['course_name' => 'required','classroom_id' => 'required']);
    
    $course = new Course();
    $course->name = $course_name;
    $course->classroom_id = $classroom_id;
    $course->save();
  
    $this->render();

}

CodePudding user response:

you can use rule unique

...
$this->validate([
    'classroom_id' => 'required|{TableName}',
]);
...

reference https://laravel.com/docs/8.x/validation#rule-unique

CodePudding user response:

you can achieve it using the validation method "unique", and define in it the table and column which you're going to check

$this->validate([
  'course_name' => 'required',
  'classroom_id' => 'required|unique:courses,classroom_id'
]);

on edit method, this approach changes, once you need to ignore the validation of this field if no change is made on it. Then you can do this

$this->validate([
  'course_name' => ['required']
  'classroom_id' => ['required',Rule::unique('courses','classroom_id')->ignore('id',$this->course->id)]
]);
  • Related