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
CodePudding user response:
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
CodePudding user response:
On validation rules, add the unique property like this:
'email' => 'unique|required|max:255',
And show in the blade view; there are two options, the first one is custom for each field:
@error('email')
<span>{{ $message }}</span>
@enderror
And the second is as the laravel docs:
@if ($errors->any())
<div >
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
I also recommended read Laravel docs validation