2 Column unique validation in controller in Laravel

Two Column unique validation in controller in Laravel


In Laravel, ensuring a combination of two columns is unique within a database table often arises when dealing with complex data relationships, such as enforcing that a user can only have one role within a specific organization. This scenario cannot be directly handled through Laravel's standard unique validation rule, which traditionally operates on single fields. However, Laravel is flexible enough to accommodate this requirement through custom validation logic or advanced usage of its validation features.

To implement a two-column unique validation in a Laravel controller, one effective method involves utilizing a combination of custom validation rules and querying the database to check for the existence of the specific combination of values. The approach involves creating a custom validation closure that leverages Laravel's Query Builder to search the relevant table for records matching both column values submitted by the form. If a matching record is found, the validation fails, indicating that the combination is not unique.


use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use App\Models\YourModel; // Use your actual model

public function store(Request $request)
{
    $validator = Validator::make($request->all(), [
        'client_id' => [
            'required',
            'numeric',
            function ($attribute, $value, $fail) use ($request) {
                $exists = YourModel::where('client_id', $request->client_id)
                                   ->where('user_id', $request->user_id)
                                   ->exists();
                if ($exists) {
                    $fail('The combination of client_id and user_id already exists.');
                }
            },
        ],
        'user_id' => 'required|numeric',
        // other fields...
    ]);

    if ($validator->fails()) {
        return redirect()->back()->withErrors($validator)->withInput();
    }

    // Process the data...
}

Comments

Popular posts from this blog

Axis Bank BBPS API Integration