Reputation: 5772
Currently, if there are validation errors, they're all printed at the top of the page as <li>
elements in a <ul>
element. I wanna make to so that if there's a The username field is required.
error to have it under the username input and likewise for the password error. How do I do that?
signIn view:
<ul>
@foreach ($errors->all() as $error)
<li>{{$error}}</li>
@endforeach
</ul>
<div class="wrapper">
<form action='{{ route('signin') }}' method='POST'>
<label>Username</label>
<input class='input' type='text' name='username' placeholder='Username' value='{{ Request::old('username') }}'>
<label>Password</label>
<input class='input' type='password' name='password' placeholder='Password' value='{{ Request::old('password') }}'>
{{ csrf_field() }}
<button class='Submit' type='submit'>Log In</button>
</form>
</div>
signIn function:
public function signIn(Request $request){
$this->validate($request, [
'username' => 'required|max:120',
'password' => 'required|min:5|max:12'
]);
$username = $request['username'];
$password = $request['password'];
if (Auth::attempt(['username' => $username, 'password' => $password])){
return redirect()->back();
} else {
return redirect()->back();
}
}
Upvotes: 1
Views: 100
Reputation: 3819
The optimal way would be to create a partial so you are not repeating the same block of code OR if you want to update what the error is wrapped in, it is in one place.
In views/partials, create invalid.blade.php with the following HTML
@if($errors->has($field))
<span>{{ $errors->first($field) }}</span>
@endif
This checks the errors array to make sure the error for a particular field exists. The first() method takes the first error for that field from the error array (some fields may have multiple errors).
Now, under any input field, just add the following line, replacing FIELD_NAME with the name of the input field you are directly under (ie: username)
@include('partials.invalid', ['field' => 'FIELD_NAME')
Upvotes: 2