简体   繁体   中英

Laravel 5.3 Validation unique

I currently am struggling with the validation of Laravel, especially with the unique validator.

I have a table, which holds some values, the important one now is templateUrl . What I do is, show the user a form, containing the templateUrl he entered before (after saving it) and some other values, and then he can change it or leave it as it is. This templateUrl should be unique in this table. So if the user changes this templateUrl in the form, and its not used yet, everything is fine, but if the user now tries to save it, without changing templateUrl , then the validation throws an error (because this is already saved in the table, even if its the same row...). So it seems to be not possible to save the value, even if its the same row and column.. I hope you know what I mean?

This is the code for the validation:

$this->validate($request,
            [
                'templateUrl' => 'required|unique:users'
            ],
            [
                'templateUrl.unique' => 'Diese URL ist leider schon vergeben. Bitte suchen Sie sich eine andere aus!'
            ]
        );

What can I do, to make it possible to save the value, if its the same user, that "enters" or let the value as it is? Ofcourse, no other user should be able to enter the same templateUrl , that's why I need such a validation, but if the user lets the templateUrl unchanged and just changes other fields in the form, of course it should work.

Any ideas, tricks?

You can add extra parameters to the validation to ignore a given row, in this case the current row. More information on this can be found in the documentation .

For example:

$this->validate($request,
    [
        'templateUrl' => 'required|unique:users,templateUrl,' . $user->id // Ignore rows with primary key $user->id
    ],
    [
        'templateUrl.unique' => 'Diese URL ist leider schon vergeben. Bitte suchen Sie sich eine andere aus!'
    ]
);

So you can make something like below. Check if is unique only for others users, and only if user is found. This way you can use this method in update and store method. Anyway - better move this code to Form Request .

$this->validate($request, [
        'templateUrl' => 'required|unique:users,templateUrl' . ($user === null ? '' : ',' . $user->id),
    ], [
        'templateUrl.unique' => 'Diese URL ist leider schon vergeben. Bitte suchen Sie sich eine andere aus!',
    ]
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM