Laravel 8 - All validation rules are shown if one rule applies - laravel

I am using Laravel Framework 8.62.0 and I am having the following validation rules:
$rules=[
'username' => 'required|min:3|max:30|alpha_dash',
'email' => "required|email|unique:users,email",
'password' => 'required|min:6|confirmed',
];
$error_messages=[
'username.required'=>'The username-field is required.',
'username.min'=>'Your username must be longer than 3 characters.',
'username.max'=>'Please shorten your username.',
'username.alpha_dash'=>'Please use letters from A-Z and a-z, dashes (-) or underscores(_).',
'email.unique'=>'Your email is already used.',
'email.email'=>'Please add a correct email-address.',
'email.required'=>'The email-field is required.',
'password.required'=>'The password-field is required.',
'password.min'=>'Your password must have at least 6 characters.',
'password.confirmed'=>'Your entered passwords do not match.',
];
$validator = validator($request->all(), $rules, $error_messages);
My form looks like the following:
<form id="Register" class="card-body" tabindex="500" action="{{ url('register') }}" method="POST">
<!-- CSRF Token -->
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
<div class="name">
<input type="text" name="username" value="{!! old('username') !!}">
<label>Username</label>
<li>
{!! $errors->first('username.required', '<ul><span style="color: red;" class="help-block">:message</span></ul>') !!}
{!! $errors->first('username.min', '<ul><span style="color: red;" class="help-block">:message</span></ul>') !!}
{!! $errors->first('username.max', '<ul><span style="color: red;" class="help-block">:message</span></ul>') !!}
{!! $errors->first('username.alpha_dash', '<ul><span style="color: red;" class="help-block">:message</span></ul>') !!}
</li>
</div>
<div class="mail">
<input type="email" name="email" value="{{ old('email') }}">
<label>Mail</label>
{!! $errors->first('email.unique', '<span style="color: red;" class="help-block">:message</span>') !!}
{!! $errors->first('email.required', '<span style="color: red;" class="help-block">:message</span>') !!}
{!! $errors->first('email.email', '<span style="color: red;" class="help-block">:message</span>') !!}
</div>
<div class="passwd">
<input type="password" name="password" value="{{ old('password') }}">
<label>Password</label>
{!! $errors->first('password.min', '<span style="color: red;" class="help-block">:message</span>') !!}
{!! $errors->first('password.confirmed', '<span style="color: red;" class="help-block">:message</span>') !!}
{!! $errors->first('password.required', '<span style="color: red;" class="help-block">:message</span>') !!}
</div>
<div class="passwd">
<input type="password" name="password_confirmation" value="{{ old('password_confirmation') }}">
<label>Confirm Password</label>
{!! $errors->first('password.confirmed', '<span style="color: red;" class="help-block">:message</span>') !!}
</div>
<div class="submit">
<!-- <a class="btn ripple btn-primary btn-block" href="#">Register</a> -->
<input type="submit" class="btn ripple btn-primary btn-block" value="Register">
</div>
<p class="text-dark mb-0">Already have an account?Sign In</p>
</form>
When I enter a username with 3 characters and without a - and my password lengths do not match I get all validation errors back:
However, I would only like to get the errors back that really apply.
Any suggestions what I am doing wrong?
I appreciate your replies!

You are asking the blade file to display every error that you have created by name/key, rather than seeing what's inside the error bag.
Laravel automatically presents the errors that apply to your page, and limits the output to only those that apply. You don't need to catch them individually by name as you have with $errors->first('email.unique')... etc.
Take a look at the docs on how to display validation errors, it's pretty nifty. Basically check the error bag and if they are presented, display only those that are in the bag:
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
The $errors variable is available to you on any view within a route under the web middleware.

Related

LaravelCollective does not receive the data

I am starting with Laravel 5.5.
I have an error when trying to send the data to the edit form:
`Illegal string offset 'name' (View: C: \ xampp \ htdocs \ laravel-ads \ resources \ views \ admin \ edit.blade.php)
public function edit($id)
{
//
$user = User::findOrFail($id);
//var_dump($user['name']);
return view('admin.edit', compact('user'));
}
<div class="container">
<h1 class="text center">Editor de Usuario</h1>
{!! Form::model($user, ['method' => 'PATCH', 'action' => ['AdminController#update', $user->id], 'files' => true]) !!}
<div class="form-group">
{!! Form::label('id', 'Id') !!}
{!! Form::number('id', '', ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('id_rol', 'Rol') !!}
{!! Form::number('id_rol', '', ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('imagen', 'Imagen') !!}
{!! Form::file('imagen', '', ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('name', 'Nombre') !!}
{!! Form::text('name', '', ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('email', 'Email') !!}
{!! Form::email('email', '', ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('password', 'Password') !!}
{!! Form::password('password', '', ['class' => 'form-control']) !!}
</div>
{!! Form::submit('Editar', ['class' => 'btn btn-success']) !!}
{!! Form::close() !!}
</div>
The route:
Route::resource('admin', 'AdminController');
My index.blade.php:
<div class="container-fluid"></div>
<h1 class="text-center"> Usuarios</h1>
<div class="table-responsive">
<table class="table table-dark">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Rol</th>
<th scope="col">Foto</th>
<th scope="col">Nombre</th>
<th scope="col">Email</th>
<th scope="col">Ultima actualizacion</th>
<th scope="col">Creado</th>
</tr>
</thead>
<tbody>
#foreach($users as $user)
<tr>
<th scope="row">{{$user->id}}</th>
<td>{{$user->id_rol}}</td>
<td><img src="images/{{$user->imagen}}" alt="imagen de usuario" width="150"></td>
<td> {{$user->name}}</td>
<td>{{$user->email}}</td>
<td>{{$user->updated_at}}</td>
<td>{{$user->created_at}}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
The issue jumps in this place of Laravel:
* #param string $value
* #param array $options
*
* #return \Illuminate\Support\HtmlString
*/
public function input($type, $name, $value = null, $options = [])
{
$this->type = $type;
if (! isset($options['name'])) {
$options['name'] = $name;
}
// We will get the appropriate value for the given field. We will look for the
// value in the session for the value in the old input data then we'll look
// in the model instance if one is set. Otherwise we will just use empty.
$id = $this->getIdAttribute($name, $options);
if (! in_array($type, $this->skipValueTypes)) {
$value = $this->getValueAttribute($name, $value);
}
// Once we have the type, value, and ID we can merge them into the rest of the
// attributes array so we can convert them into their HTML attribute format
// when creating the HTML element. Then, we will return the entire input.
$merge = compact('type', 'value', 'id');
This answer no works to me
I have fixed the issue without discovering its cause.
I leave here the form that does work to see if any user can tell me where the error was.
I don't know what was wrong.
As a curious fact, the previous form even and everything being commented continued giving the issue.
<form method="POST" action="{{route('admin.update',$user->id)}}" enctype="multipart/form-data">
#csrf
#method('PUT')
<div class="form-group row">
<label for="name" class="col-md-4 col-form-label text-md-right">{{ __('Name') }}</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control #error('name') is-invalid #enderror" name="name" value="{{ $user->name }}" autocomplete="name" autofocus>
#error('name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="id_rol" class="col-md-4 col-form-label text-md-right">{{ __('Rol') }}</label>
<div class="col-md-6">
<input id="id_rol" type="number" class="form-control #error('id_rol') is-invalid #enderror" name="id_rol" value="{{ $user->id_rol }}" autocomplete="id_rol" autofocus>
#error('id_rol')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ $user->email }}" autocomplete="email">
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<img class="col-md-4 col-form-label text-md-right" src="../../../public/images/{{$user->imagen}}" alt="imagen de usuario" width="150">
<div class="col-md-6">
<input id="imagen" type="file" class="form-control #error('imagen') is-invalid #enderror" name="imagen" value="{{ $user->imagen }}" autocomplete="imagen">
#error('imagen')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="col-md-2">
<button type="submit" class="btn btn-primary">
{{ __('Guardar') }}
</button>
</div>
</div>
</form>

In Laravel how to show error message beside specific field?

I am new to laravel. I created a simple page where a user can add a product to the database. If the product title or amount is empty; I can also show the errors. But I want to show error right beside the specific field. If the title is empty the error will show beside the title field.
I searched and found solutions using JS and some other. But is there a way to achieve this using only laravel?
my view is like this
<form method="POST" action="create">
#csrf
<input type="text" name="title" placeholder="Product name"><br>
<textarea name="description" placeholder="Description"></textarea><br>
<input type="string" name="amount" placeholder="Price per unit"><br>
<button type="submit">Add Product</button>
</form>
#if(count($errors))
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
#endif
and my controller is like this
public function store()
{
$this->validate(request(),[
'title'=> 'required',
'amount' => 'required',
]);
$product = new Product;
$product->title = request('title');
$product->seller_id = Auth::guard('seller')->user()->id;
$product->description = request('description');
$product->amount = request('amount');
$product->save();
return redirect('/dashboard');
}
You need to check for errors and display wherever you want like given below
#if ($errors->has('title')) <p style="color:red;">{{ $errors->first('title') }}</p> #endif
and
#if ($errors->has('amount')) <p style="color:red;">{{ $errors->first('amount') }}</p> #endif
In your code for view it can be placed as
<form method="POST" action="create">
#csrf
<input type="text" name="title" placeholder="Product name">
#if ($errors->has('title')) <p style="color:red;">{{ $errors->first('title') }}</p> #endif <br>
<textarea name="description" placeholder="Description"></textarea><br>
<input type="string" name="amount" placeholder="Price per unit">
#if ($errors->has('amount')) <p style="color:red;">{{ $errors->first('amount') }}</p> #endif <br>
<button type="submit">Add Product</button>
</form>
Additionally you can also print custom messages by returning the error text from controller as shown below
$customMessages = [
'title.required' => 'The title field is required to be filled',
'amount.required' => 'The amount field should be completely filled'
];
$this->validate(request,[
'title'=> 'required',
'amount' => 'required',
], $customMessages);
Instead, if you want to show all the errors for a field you can print them as follows
#if ($errors->has('title'))
<p style="color:red;">
#foreach ($errors->get('title') as $errormessage)
{{ $errormessage }}<br>
#endforeach
</p>
#endif
All errors you can get in $errors array
just get them by input field name
Example:
<div class="form-group {{ $errors->has('title') ? 'has-error' : ''}}">
<label for="titile" class="col-sm-3 control-label">Title: </label>
<div class="col-sm-6">
<input class="form-control" placeholder="Product name" required="required" name="title" type="text" id="title">
{!! $errors->first('title', '<p class="help-block">:message</p>') !!}
</div>
</div>
Here, $errors->first('title') mean its getting the first index of title errors in $errors array.
in your view you can do this as:
<form method="POST" action="create">
#csrf
<input type="text" name="title" placeholder="Product name"><br>
{!! $errors->first('title', '<p class="help-block">:message</p>') !!}
<br>
<textarea name="description" placeholder="Description"></textarea><br>
{!! $errors->first('description', '<p class="help-block">:message</p>') !!}
<br>
<input type="string" name="amount" placeholder="Price per unit"><br>
{!! $errors->first('amount', '<p class="help-block">:message</p>') !!}
<br>
<button type="submit">Add Product</button>
</form>

How to seperate validation error list in laravel

Code in blade
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Name: <input type="text" name="name">
Phone: <input type="text" name="phone">
Email: <input type="text" name="email">
Validation Code
$data = $this->validate($request,[
'name' => 'required',
'phone' => 'required',
'email' => 'required',
]);
I wanna display each error under its input field.
You have to add error message after input field
<div class="form-group {{ $errors->has('name') ? 'has-error' : ''}}">
<label for="name" class="col-sm-3 control-label">Name: </label>
<div class="col-sm-7">
<input class="form-control" required="required" name="name" type="text" id="name">
{{ $errors->first('name', '<p class="help-block">:message</p>') }}
</div>
</div>
To display each error seperatly you can just use $errors->first() and pass in the field name you're requesting. See the following example.
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Name: <input type="text" name="name">
{{ $errors->first('name') }}
Phone: <input type="text" name="phone">
{{ $errors->first('phone') }}
Email: <input type="text" name="email">
{{ $errors->first('email') }}
Notice after each field I call $errors->first()
Name: <input type="text" name="name">
<small class="text-danger">{{ $errors->first('name') }}</small>
Phone: <input type="text" name="phone">
<small class="text-danger">{{ $errors->first('phone') }}</small>
Email: <input type="text" name="email">
{{ $errors->first('email') }}
If condition is not needed if u don't want to show all errors at a place.
Also, two types the error message can be display
{{ $errors->first('name') }}
<small class="text-danger">{{ $errors->first('phone') }}</small>

Laravel 5 - How to send url paramaters in form

I have a form with some input in a search page who has an URL with many parameters and I want to send them in this form or any other way .
Form code
{!! Form::open(['route' => ['test.mail'],'method' => 'post','files' => true]) !!}
{!! Form::token() !!}
<div class="box-header">
<i class="fa fa-envelope"></i>
<h3 class="box-title">Quick Email</h3>
<!-- tools box -->
<div class="pull-right box-tools">
<!--<button class="btn btn-info btn-sm" data-widget="remove" data-toggle="tooltip" title="Remove"><i class="fa fa-times"></i></button>-->
</div><!-- /. tools -->
</div>
<div class="box-body">
<div class="form-group">
<input type="text" class="form-control" name="object" placeholder="Subject" />
</div>
<div class="form-group">
<textarea class="textarea" name="textu" placeholder="Message" cols="120" rows="8"></textarea>
</div>
<div class="form-group">
<input type="file" class="form-control" name="filee" />
</div>
</div>
<div class="box-footer clearfix">
<input type="submit" name="sendEmail" class="pull-right btn btn-default" id="sendEmail" value="Send">
</div>
{!! Form::close() !!}
This is how you get all the values in your url
foreach($_GET as $key=>$value){
echo $key, ' => ', $value, "<br/>n";
}
then to send them in your form you simply create an input type hidden like this:
<input id="someId" name="UrlValue" type="hidden" value="$UrlValue">
I hope this will help,
// Get the current URL without the query string...
echo url()->current();
// Get the current URL including the query string...
echo url()->full();
// Get the full URL for the previous request...
echo url()->previous();
Each of these methods may also be accessed via the URL facade:
use Illuminate\Support\Facades\URL;
echo URL::current();
https://laravel.com/docs/5.6/urls

Laravel multiple insert in a table

I want to create a post and be able to add different categories, so I made this code
public function store(Request $request)
{
$this->validate($request,[
'title' => 'required',
'body' => 'required',
'name'=>'required'
]);
$post = new \App\Post([
'title' => $request->get('title'),
'body' => $request->get('body')
]);
$post->save();
foreach ($request->name as $data) {
$categories = new \App\Category();
$categories->name = $request->get('name');
//dd($categories);
$post->categories()->save($categories);
}
return redirect()->route('create');
}
model Post
public function categories(){return $this->hasMany(\App\Category::class, 'post_id');}
model Category
public function something(){return $this->belongsTo(\App\Solicitud::class, 'post_id');}
HTML
<form class="form-horizontal" role="form" method="POST" action="{{ route('store_data') }}">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('title') ? ' has-error' : '' }}">
<label for="title" class="col-md-4 control-label">title:</label>
<div class="col-md-6">
<input type="text" name="title" placeholder="Cantidad" class="form-control" value="{{ old('title') }}" />
#if ($errors->has('title'))
<span class="help-block">
<strong>{{ $errors->first('title') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('body') ? ' has-error' : '' }}">
<label for="body" class="col-md-4 control-label">Body:</label>
<div class="col-md-6">
<input type="text" name="body" placeholder="Cantidad" class="form-control" value="{{ old('body') }}" />
#if ($errors->has('body'))
<span class="help-block">
<strong>{{ $errors->first('body') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
<table class="table table-bordered" id="dynamic_field">
<thead>
<tr>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="name[]" placeholder="Name" class="form-control name_list" value="{{ old('name') }}" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success"> + </button></td>
</tr>
</tbody>
</table>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Create
</button>
</div>
<div class="col-md-6 col-md-offset-4">
<a class="btn btn-info" href="{{ URL::previous() }}">back</a> <br>
</div>
</div>
</form>
Scritps :
<script>
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="name[]" placeholder="Name" class="form-control name_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">-</button></td></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
});
</script>
but I get this error. when I submit the form
Type error: Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type array, integer given, called in C:\xampp\htdocs\proyect\vendor\laravel\framework\src\Illuminate\Database\Query\Grammars\Grammar.php on line 681.
"Type error: Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type array, integer given, called in C:\xampp\htdocs\proyect\vendor\ ▶"
and if press submit with the input empty I get this error
htmlspecialchars() expects parameter 1 to be string, array given (View: C:\xampp\htdocs\proyect\resources\views\create.blade.php)
but if I edit the code, in this way it works but adds only one category.
$categories = new \App\Category();
$categories->name = $request->get('name');
//dd($categories);
$post->categories()->save($categories);
I hope I have explained well and thanks :)

Resources