how to create an alert if the same data has been added using laravel?

Issue

I made an add user feature, but if I add the same data there will be a problem, I want to limit the duplicate data, how to create a warning if the same data has been added?

Source Code UserController

<?php

namespace App\Http\Controllers;

use App\Traits\ImageStorage;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Yajra\DataTables\Facades\DataTables;

class UserController extends Controller
{
    ...

    public function create()
    {
        return view('pages.user.create');
    }

    public function store(Request $request)
    {
        $validateData = $request->validate([
            'name' => 'required|max:255',
            'email' => 'required|max:255',
            'password' => 'required|max:255',
            'is_admin' => 'required',
        ]);

        $photo = $request->file('image');

        if ($photo) {
            $request['photo'] = $this->uploadImage($photo, $request->name, 'profile');
        }

        $request['password'] = Hash::make($request->password);

        User::create($request->all());

        return redirect()->route('user.index');
    }
    ...
}

Screenshot Error
Image

Solution

There are two ways to do it. First is to add ‘unique’ to your validation. For example:

$validateData = $request->validate([
        'name' => 'required|max:255|',
        'email' => 'required|max:255|unique:users,email',
        'password' => 'required|max:255',
        'is_admin' => 'required',
 ]);

or you can manually check if the user already exists by adding an if statement like this:

if (!User::where('email', $request->input('email'))->get()->isEmpty()) {
        // user with that email already exists
}

Reference for the first example: Laravel unique validation

Answered By – Stefano Christian Wiryana

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published