How to check that entered value of one these form inputs are not repeated at the other input

37 views Asked by At

I have added this Controller method and I need to make sure that the entered number for one of the inputs (banner_one_priority, banner_two_priority, banner_three_priority, banner_four_priority, banner_five_priority) are not repeated at the other input.

public function updateBannerPriorities(Request $request, $id)
    {
        $data = $request->validate([
            'banner_one_priority' => 'required|digits_between:1,5',
            'banner_two_priority' => 'required|digits_between:1,5',
            'banner_three_priority' => 'required|digits_between:1,5',
            'banner_four_priority' => 'required|digits_between:1,5',
            'banner_five_priority' => 'required|digits_between:1,5',
        ]);
            
        DB::table('static_pages_field')->where('spf_page_type', 'slider')->where('spf_field_name', 'spf_home_banner1')->update([
            'spf_field_value' => $request->banner_one_priority
        ]);
        
        DB::table('static_pages_field')->where('spf_page_type', 'slider')->where('spf_field_name', 'spf_home_banner2')->update([
            'spf_field_value' => $request->banner_two_priority
        ]);
        
        DB::table('static_pages_field')->where('spf_page_type', 'slider')->where('spf_field_name', 'spf_home_banner3')->update([
            'spf_field_value' => $request->banner_three_priority
        ]);
        
        DB::table('static_pages_field')->where('spf_page_type', 'slider')->where('spf_field_name', 'spf_home_banner4')->update([
            'spf_field_value' => $request->banner_four_priority
        ]);
        
        DB::table('static_pages_field')->where('spf_page_type', 'slider')->where('spf_field_name', 'spf_home_banner5')->update([
            'spf_field_value' => $request->banner_five_priority
        ]);
        
        return redirect()->back();
    }

For example if user has entered 1 for banner_one_priority input field, he can not enter that number again for banner_two_priority...

So how to check that in the Form validation?

1

There are 1 answers

0
Mohammad Salehi On

You can treat your inputs as an array and use distinct rule.
In your blade files, you have to write something like this:

<input name="priority[banner_one]">
<input name="priority[banner_two]">

and your validation should be something like this:

$data = $request->validate([
    'priority' => 'required|array',
    'priority.*' => 'required|digits_between:1,5|distinct',
]);

from Laravel doc: https://laravel.com/docs/9.x/validation#rule-distinct