Validate unique name and firstname in Laravel

倖福魔咒の 提交于 2021-02-11 14:41:11

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!