Skip to content
Advertisement

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

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 AppHttpControllers;

use AppTraitsImageStorage;
use AppUser;
use IlluminateHttpRequest;
use IlluminateSupportFacadesHash;
use YajraDataTablesFacadesDataTables;

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

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement