2

I know this question asked before but i want to know how can i stop to showing this error and instead of this i want to show custom error message to user in blade.

This is user migration :

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('image')->nullable();
        $table->string('email')->unique();
        $table->boolean('is_superuser')->default(0);
        $table->boolean('is_staff')->default(0);
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->string('phone_number')->nullable()->unique();
        $table->enum('two_factor_type', ['off', 'sms']);
        $table->string('melli')->nullable()->unique();
        $table->rememberToken();
        $table->timestamps();
    });
}

UPDATE: This is my insert function :

$user = User::find(auth()->user()->id);
$request->validate([
    'melli' => 'min:10|max:10',
    'cart' => 'min:16|max:16'
]);;
$user->update([
    'name' => $request['name'],
    'cart' => $request['cart'],
    'melli' => $request['melli'],
    'gender' => $request['gender']
]);
return redirect(route('profile.index'));

This error happens when i have a melli in my database like 1234567890 and i try to write 1234567890 again, because the melli field is unique.

Pooriya Mostaan
  • 257
  • 1
  • 5
  • 21
  • 2
    You don't show your insert query, but I'd suggest using a try/catch block, or look for an existing Melli string before inserting. – aynber Sep 01 '20 at 13:53
  • Normally you would handle such state during validation, and return custom messages to blade. If you want to handle it yourself, then as @aynber suggested, catch the exception and return your own message to plade – user3532758 Sep 01 '20 at 13:56
  • Question updated – Pooriya Mostaan Sep 01 '20 at 13:57
  • 3
    Use `unique` validation in melli field. https://laravel.com/docs/7.x/validation#rule-unique check this as well to handle update https://stackoverflow.com/a/48492198/12459934 – Avi Sep 01 '20 at 14:05
  • Thank you all answers is helpful – Pooriya Mostaan Sep 01 '20 at 14:28

1 Answers1

2

You need unique validation rule and ignore that id in the update.

You can do like this:

$request->validate([
   'melli' => 'min:10|max:10|unique:users,melli,' .$user->id,
]);

Or

$request->validate([
    'melli' => [
        'min:10',
        'max:10',
        Rule::unique('users')->ignore($user->id, 'id')
    ],
    'cart' => 'min:16|max:16'
]);

I think that's what you need.

Also, some helpful answer.

mare96
  • 3,749
  • 1
  • 16
  • 28