问题
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');
}
回答1:
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.
来源:https://stackoverflow.com/questions/55856668/validate-unique-name-and-firstname-in-laravel