Hi guys,
I will show you Laravel unique validation with softdelete.Unique validation in check without delete_at column.Soft deleted record with the same name exists but not check in unique validation.
You can create categories table.
Solution Unique Validation
Step 1 : Create Blade File
you can create blade file.
resources\views\category\index.blade.php
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
@if (count($errors) > 0)
<ul>
@foreach($errors->all() as $error)
<li>{{ $error }} </li><br>
@endforeach
</ul>
@endif
<form action="{{ route('category.store') }}" method="post">
@csrf
<label>Name:</label>
<input type="text" name="name">
<br>
<br>
<label>City:</label>
<input type="text" name="city">
<br>
<br>
<label>Mobile No:</label>
<input type="text" name="mno">
<br>
<br>
<button type="submit">Save</button>
</form>
<br>
<br>
<br>
<br>
<table border="2" width="50%">
<tr>
<th>No</th>
<th>Name</th>
<th>City</th>
<th>Mobile No</th>
<th>Action</th>
</tr>
<?php $no = 1; ?>
@foreach($categories as $key => $value)
<tr style="text-align: center;">
<td>{{ $no }}</td>
<td>{{ $value->name }}</td>
<td>{{ $value->city }}</td>
<td>{{ $value->mno }}</td>
<td><a href="{{ route(" target="_blank" rel="nofollow" category.destroy',[$value->id]) }}"><button>Delete</button></a></td>
<?php $no++; ?>
</tr>
@endforeach
</table>
</body>
</html>
Step 2 : Create Controller File
you can create controller file.
App/http/controller/CategoryController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Category;
class CategoryController extends Controller
{
public function index()
{
$categories = Category::get();
return view('category.index',compact('categories'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'name'=>'required',
'city'=>'required|unique:categories,city,Null,id,deleted_at,NULL',
'mno'=>'required|numeric',
]);
$input = $request->all();
Category::create($input);
return redirect(route('category.index'));
}
public function destroy($id)
{
Category::find($id)->delete();
return redirect(route('category.index'));
}
Step 3 : Add Route in web.php
In this step, we will add routes to handle request.
routes\web.php
Route::get('category','[email protected]')->name('category.index');
Route::post('category','[email protected]')->name('category.store');
Route::delete('category/{id}','[email protected]')->name('category.destroy');
It will help you...