Jannat Pia
Jannat Pia

Reputation: 39

How to custom validation with input value as name already been taken?

In controller

public function store(Request $req)
{
    $req->validate([
    'username' => 'required|unique:users',
    ]);

    $users = new Users();
    $users->username = $req->username;
    $users->save();        
    return redirect()->route('list.users');
}

The username validation return as The username has already been taken.

I am typing the username field as JHON and i would to return the validation as like: The JHON has already been taken. ?

Upvotes: 0

Views: 1412

Answers (3)

Sogeking
Sogeking

Reputation: 830

To make your code cleaner, you should change the localization of the "unique" validation error

Go to the file "resources/lang/en/validation.php" (or change the "en" part with your language's iso code) and change the "unique" value.

From:

'unique' => 'The :attribute has already been taken.',

To:

'unique' => 'The :attribute :input has already been taken.',

This way, you should get the following message

The username JHON has already been taken.

Upvotes: 1

Robert Kujawa
Robert Kujawa

Reputation: 997

I believe you can use :input when defining custom validation messages.

public function store(Request $req)
{
    Validator::make($req, [
        'username' => 'required|unique:users',
    ], [
        'unique' => 'The :input username has already been taken.',
    ]);

    $users = new Users();
    $users->username = $req->username;
    $users->save();        
    return redirect()->route('list.users');
}

Upvotes: 1

Commander
Commander

Reputation: 264

$req->validate([
    'username' => 'required|unique:users,username',
    ]);

This is the syntax for using unique:

unique:table,column

https://laravel.com/docs/7.x/validation#rule-unique

Upvotes: 0

Related Questions