Laravel Unique Validation with Soft Delete Example

10-Apr-2023

.

Admin

Hello Guys,

I will explain step by step tutorial How To Make Unique Validations Work With Soft Delete In Laravel. It's a simple example of Laravel Validation Unique with Soft Delete. Here you will learn laravel validation unique soft delete. It's a simple example of laravel soft delete 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('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','CategoryController@index')->name('category.index');

Route::post('category','CategoryController@store')->name('category.store');

Route::delete('category/{id}','CategoryController@destroy')->name('category.destroy');

It will help you...

#Laravel

#Laravel 6