Show duplicate error message in list of errors in view: Laravel 5

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

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

Is there a way to insert this error message into the validation rule so that this error message appears in the error list view in the next section?

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

Solution: 1

Ref: unique: Table name:

Ensure that the database table contains a 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();

}
+2
source

Try

Create Class CategoryFormRequest

namespace App\Http\Requests;

use App\Http\Requests\Request;
use Illuminate\Support\Facades\Input;

class CategoryFormRequest extends Request {

    public function authorize() {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules() {
        $rules = [
            'Category' => ' required|unique:categories,Category',
        ];
        if ($this->method() == 'PUT') {
            $rules['Category'] = 'required|unique:categories,Category,' . $this->category;
        }
        return $rules;
    }

}

Your controller code

use App\Http\Requests\CategoryFormRequest as CategoryFormRequest;
......
......
 public function store(CategoryFormRequest  $request) {
  .......
  ....... 
}

Link: - Request class in laravel

0
source

:

return view('my_view')->withErrors(['Duplicate Record.']);
0

Source: https://habr.com/ru/post/1619792/


All Articles