user11124425
user11124425

Reputation: 971

Validate unique name and firstname in Laravel

I know the subject exists, but I haven't found a solution so far. I have a table which is named players with two fields: name, firstname. My goal is to have neither duplicate when I enter several entries.

I want to get this result.

Fostier | Alain 
Fostier | Jeremy 

If I have two times Fostier | Alain it's not correct.

The duplicate system should combine only the ID? I have tried the following without success.

public function store(Request $request)
{
    $request->validate([
        'name' => 'required|unique:players,name',
        'firstname' => 'required|unique:players,firstname',

    ]);
    Player::create($request->all());

    flashy('Valider');

    return redirect()->route('players.index')
        ->with('success', 'save');
}

Upvotes: 0

Views: 1629

Answers (1)

omitobi
omitobi

Reputation: 7334

You can use the Illuminate\Validation\Rule class to make compound check e.g:

use Illuminate\Validation\Rule;
...

$request->validate([
    'name' => ['required', Rule::unique('players', 'name')->where(function ($query) use ($request) {
        return $query->where('name','!=', $request->input('firstname'));
    })],
    'firstname' => ['required', Rule::unique('players', 'firstname')->where(function ($query) use ($request) {
        return $query->where('firstname', '!=', $request->input('name'));
    })],
]);

This checks uniqueness of the 'firstname' by also checking if the 'name' is in use, and also does the same for 'name' checking the 'firstname' with it.

Upvotes: 3

Related Questions