Show duplicate error message in the list of errors in View: Laravel 5

advertisements

Below is my code to check if the record is duplicate or not.

$Category = \App\Models\Category_Model
           ::where("Category", "=", $request->input('Category'))->first();
if($Category != null) {
    return 'Duplicate';
}

Is there any way to inject this error message in the validation rule in such a way that this error message appears in View the error list in below section?

@if (count($errors) > 0)
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif


Solution:1

Reference : unique:Name of the Table:

Make sure the database table contains Unique Constraint.

$v = Validator::make($request->all(), [
    'Category' => 'required|unique:tblcategory|max:100|min:5'
]);

Solution:2

$Category = \App\Models\Category_Model
            ::where("Category", "=", $request->input('Category'))->first();

if($Category != null) {

    $v->errors()->add('Duplicate', 'Duplicate Category found!');

    return redirect('Create-Category')
                ->withErrors($v)
                ->withInput();

}