You need to configure your application so that at the time of the request the validation of your model is done, a minimal example with validation:
The Model
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class ListaStorm extends Model
{
protected $table = 'listastorm';
protected $primaryKey = 'id';
protected $fillable = ['id_uc'];
public $timestamps = false;
}
Validation class
In the validation class, two essential validations are placed: required
This means that the data is mandatory and unique
with the paramenter of the table name means that this data can not be repeated:
<?php namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ListaStormRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return ['id_uc' => 'required|unique:listastorm'];
}
}
The Controller
<?php namespace App\Http\Controllers;
use App\Http\Requests\ListaStormRequest;
use App\ListaStorm;
use Illuminate\Http\Request;
class ListaStormController extends Controller
{
public function index()
{
return view('lista', ['items' => ListaStorm::all()]);
}
public function create()
{
return view('create');
}
public function store(ListaStormRequest $request)
{
ListaStorm::create($request->only('id_uc'));
return redirect(route('lista.index'));
}
}
with the appropriate routes that in the example case are 3:
Route::get('lista',['as'=>'lista.index','uses'=>'ListaStormController@index']);
Route::get('lista/create',['as'=>'lista.create','uses'=>'ListaStormController@create']);
Route::post('lista/store',['as'=>'lista.store','uses'=>'ListaStormController@store']);
Your Views:
-
index.blade.php
@extends('layouts.app')
@section('content')
<div>
@foreach($items as $item)
<p> {{$item->id}} . {{$item->id_uc}} </p>
@endforeach
</div>
@endsection
-
create.blade.php
@extends('layouts.app')
@section('content')
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<div>
<form action="{{route('lista.store')}}" method="post">
{{ csrf_field() }}
<input type="text" id="id_uc" name="id_uc">
<button type="submit">Salvar</button>
</form>
</div>
@endsection
At the time of submitting the form if the data already exists it returns in View Create and displays the message:
Asintendedbythequestiondata.
References: