Unique Data in Laravel

Viewed 25

I have data like this

enter image description here

How to validate, if the user chooses same Kode, or user chooses a Kode that has conflicting Hari or Jam.

My Controller

public function store(Request $request)
    {
        $validate   =   Validator::make($request->all(), [
                            'kode_matkul'   =>  'required',
                        ]);

        if($validate->fails()) {
            return response()->json(['errors' => $validate->errors()]);
        }
    }

My View Blade

<tbody>
  @foreach ($mapel as $row)
    <tr>
      <td class="text-center">{{ $row->course }}</td>
      <td>{{ $row->course_name }}</td>
      <td class="text-center">{{ $row->sks }}</td>
      <td class="text-center">{{ $row->kelompok }}</td>
      <td>{{ $row->name }}</td>
      <td class="text-center">{{ $row->hari }}</td>
      <td class="text-center">{{ date('H:i', strtotime($row->start_time)) . ' - ' . date('H:i', strtotime($row->end_time)) }}</td>
      <td class="text-center">{{ $row->ruangan }}</td>
      <td class="text-center">
        <input class="form-check-input" type="checkbox" name="kode_matkul[]" id="kode_matkul" value="{{ $row->course }}">
      </td>
    </tr>
  @endforeach
</tbody>

Thank you

1 Answers

Please refer to https://laravel.com/docs/9.x/validation#form-request-validation for more information, but basically your steps would be -

  1. create a store request for mapel (i guess?) with something like -

    php artisan make:request StoreMapelRequest

  2. In this newly create store request, you should create a rule for uniqueness to your desired fields -

    public function rules()
    {
        return [
            'Kode' => 'required|unique:mapels|max:255',
            'Hari' => 'required|unique:mapels|max:255',
            'Jam' => 'required|unique:mapels|max:255',

        ];
    }

Edit: You can also add a simple |unique on your current store request, like this -

public function store(Request $request)
    {
        $validate   =   Validator::make($request->all(), [
                            'kode_matkul'   =>  'required|unique:mapels',
                        ]);

        if($validate->fails()) {
            return response()->json(['errors' => $validate->errors()]);
        }
    }
  • Please notice that I assume that your table name is 'mapels', in which you are seeking this uniqueness rule.
Related