I’m trying to validate a request from form and appear a problem, not showing error messages on the view.
The validation succeeds, refreshing the view but not displaying errors. Apparently $errors is always empty
I tested it on fresh installation.
Laravel Version: 5.8.33
PHP Version: 7.3.8
Database Driver & Version: mysql 5.7.22
Form is this
@section('content')
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $message)
<li>{{ $message }}</li>
@endforeach
</ul>
</div>
@endif
<form class="form-group" method="POST" action="/trainers" enctype="multipart/form-data">
@csrf
<div class="form-group">
<label for="">Nombre</label>
<input type="text" name="name" value="@isset($trainer->name){{$trainer->name}}@endisset" class="form-control">
</div>
<div class="form-group">
<label for="">Slug</label>
<input type="text" name="slug" value="@isset($trainer->slug){{$trainer->slug}}@endisset" class="form-control">
</div>
<div class="form-group">
<label for="">Descripción</label>
<input type="text" name="description" value="@isset($trainer->description){{$trainer->description}}@endisset" class="form-control">
</div>
<div class="form-group">
<label for="">Avatar</label>
<input type="file" name="avatar">
</div>
<button type="submit" class="btn btn-primary">Guardar</button>
</form>
@endsection
The store function with validation is this
public function store(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|max: 10',
'avatar' => 'required|image',
'slug' => 'required',
'description' => 'required',
]);
$trainer = new Trainer();
$file = $request->file('avatar');
if ($file != "") {
$name = time().$file->getClientOriginalName();
$file->move(public_path().'/images/', $name);
}
else{
$name = "Sin Imagen.jpg";
}
// return $name; //Ver nombre archivo
$trainer->name = $request->input('name');
$trainer->avatar = $name;
$trainer->description = $request->input('description');
$trainer->slug = $request->input('slug');
$trainer->save();
return 'Saved';
}
UPDATE
Add {{ $errors }} in blade and return [], $errors is empty
6
Answers
It's strange but solve the problem by changing local server. I used XAMPP and now I use MAMP and everything works perfect. If you are working locally with Laravel I recommend not using XAMPP.
try this
Instead of using
$request->validate
edit your code and Use
$this->validate
or this code instead:should add to method withError()
As above
if page refresh means error object not empty…and your validation code in controller work so check html code with inspect element in browser.maybe error box is hidden or for test it you can use this code in your blade