Laravel 5.4 array validation as single field message - laravel

I have following situation, the problem is validation error occurring twice because there are two different fields. The requirement is, there should be only once "User is required."
HTML:
<input type="text" name="user[]" placeholder="First Name">
<input type="text" name="user[]" placeholder="Last Name">
Form Request:
public function rules()
{
return [
'user.*' => 'required|min:3',
];
}
public function messages()
{
return [
'user.*' => 'User is required',
];
}
Validation Output:
/**
* User is required field.
* User is required field.
*/

It was an urgent task so I have done it as follows.
HTML:
<input type="text" name="user_data[]" placeholder="First Name">
<input type="text" name="user_data[]" placeholder="Last Name">
Form Request:
public function rules()
{
$user = \Request::input('user_data');
$rules = [];
if ($user[0] === null || $user[1] === null) {
$rules['user'] = 'required';
}
return $rules;
}
public function messages()
{
return [
'user.required' => 'User is required'
];
}
Validation Output:
/**
* User is required
*/

Well, the request itself contains two fields named user[], and thus will validate the field twice.
What you can do is, make two text fields
firstName
lastName
Then before saving, make
$fullname=$request->firstName().' '.$request->lastName();
$user->user=$fullname;
$user->save();

Related

How to insert record in 2 tables using single form (Laravel)?

CONTROLLER
public function store_resto(Request $request){
// dd($request->all());
$restaurant = new Restaurant();
$restaurant->name = $request->input('name');
$restaurant->email = $request->input('email');
$restaurant->address = $request->input('address');
$restaurant->save();
$image = $request->hasfile('image');
$photo = rand(1,9999).'.'.$image;
$path = public_path().'/files/';
$image->move($path, $photo);
RestoImage::create([
'image'=>$image,
'resto_id'=>$restaurant->id,
]);
$request->session()->flash('status', 'Restaurant added successfully');
return redirect('list');
}
VIEW FILE
<form method="post" action="{{route('store_resto')}}" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label>Resto Name</label>
<input type="name" name="name" class="form-control">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control">
</div>
<div class="form-group">
<label>Address</label>
<input type="text" name="address" class="form-control">
</div>
<div class="form-group">
<label>Image</label>
<input type="file" name="image" class="form-control">
</div><br>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
RestoImage Model
class RestoImage extends Model
{
use HasFactory;
protected $fillable = ['image','resto_id'];
public function restaurants(){
$this->belongsTo(Restaurant::class, 'resto_id');
}
}
Restaurant Model
class Restaurant extends Model
{
use HasFactory;
public $timestamps = false;
public function menus(){
$this->hasMany(Menu::class);
}
public function restoimage(){
$this->hasOne(RestoImage::class, 'resto_id');
}
}
Each restaurant will have 1 image. When an admin submits the form, 1 record should be inserted in both tables i.e. restaurants and resto_images. I tried this way but when I submit the form, It shows error "Call to a member function move() on bool". Please correct me if I am doing wrong. Thanks in advance.
Here i Worked on your code to explain how these things works.This is an example can help you. Not for two you can add so many tables from one function of controller. Approve my answer if you find solution or reason for getting error.
You have error because code doesn't find your image format or mine:type(png, jpeg)
$photo = rand(1,9999).'.'.$image;
Solution- you have to get image format or extention by this code
$extention = $emp_image_file->getClientOriginalExtension();
Your solution should be like this
$path1 = 'assets/img/emp/';
$destinationPath1 = $path1;
$photo_file = $request->file('image');
$photo='';
if($photo_file){
$file_size = $photo_file->getSize();
$image_name = $photo_file->getClientOriginalName();
$extention = $photo_file->getClientOriginalExtension();
$photo = value(function() use ($photo_file){
$filename = time().'.'. $photo_file->getClientOriginalExtension();
return strtolower($filename);
});
$photo_file->move($destinationPath1, $photo);
}
Put js in your view file
<script type="text/javascript">
function readURL(input) {
if (input.image && input.image[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#imagePreview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
This is you input
<input type="file" class="form-control" name="image" >
I Also Worked For Other Visitors See Once
public function store_resto(Request $request){
<!-- validation code begins -->
$this->validate($request, [
'name'=>'required|max:120',
'email'=>'required|email|unique:users',
]);
<!-- validation code ends -->
$data = $request->all();
$table1 = Required_Model1::create([
'name' =>$data['emp_name'],
'email' =>$data['email'],
]);
$table2 = Required_Model2::create([
'name' => $data['emp_name'],
'code' => $data['emp_code'],
'status' => $data['emp_status'],
'email' => $data['email'],
'gender' => $data['gender'],
'table1_id' => $table1->id,
]);
$table3 = Required_Model3::create([
'role' => $data['role'],
'table1_id' => $table1->id,
'table2_id' => $table2->id,
if(isset($table1, $table2, $table3)) {
$request->session()->flash('status', 'Restaurant added successfully');
return redirect()->route('employee-manager');
}else{
return redirect()->back();
}
}
Comment or delete this part of code if you doesn't want to validate or mandatory.
$this->validate($request, [
'name'=>'required|max:120',
'email'=>'required,
]);
Above code explains
column name must be filled with 120 characters or not be blank.
column email must be filled.
if these two doesn't satisfy it will redirect back.
This below code
If validation is set like above code this will check and work as defined. If validation is set they check two fields name and email, if they filled or not blank it will proceed further. If validation is set fields are not filled or blank they redirect back. If validation is not set it will proceed further.
if(isset($table1, $table2, $table3)) {
$request->session()->flash('status', 'Restaurant added successfully');
return redirect()->route('employee-manager');
}else{
return redirect()->back();
}
Change these two lines
<input type="name" name="name" class="form-control" required="true" />
<input type="email" name="email" class="form-control" required="true" />
Model 1 should be like this
class Required_Model1 extends Model
{
protected $fillable = ['name','email'];
}
Model 2 should be like this
class Required_Model2 extends Model
{
protected $fillable = ['name','code', 'status', 'email', 'gender', 'table1_id'];
}
Model 3 should be like this
class Required_Model3 extends Model
{
protected $fillable = ['role','table1_id', 'table2_id'];
}
Let's talk on your error as you posted
You have face error because you want to move your image name in form of boolean. Here is gave you an standard code you can use it
$path1 = 'assets/img/emp/';
$destinationPath1 = $path1;
$emp_image_file = $request->file('employee_images');
$emp_image='';
if($emp_image_file){
$file_size = $emp_image_file->getSize();
$image_name = $emp_image_file->getClientOriginalName();
$extention = $emp_image_file->getClientOriginalExtension();
$emp_image = value(function() use ($emp_image_file){
$filename = time().'.'. $emp_image_file->getClientOriginalExtension();
return strtolower($filename);
});
$emp_image_file->move($destinationPath1, $emp_image);
}
Put this in which table you wanted to save
'photo' => $emp_image,
Add this in your view make sure you edit like your requirement
<script type="text/javascript">
function readURL(input) {
if (input.employee_images && input.employee_images[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#employee_imagesPreview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
This is input
<input type="file" class="form-control" name="employee_images" >
$image = $request->hasfile('image');
This method is a boolean method. It will return true/false. Instead use
$request->file('image');
So first, here:
$image = $request->hasfile('image');
You are setting $image to a boolean by checking if it has that file and then later you want to run move on a that boolean which is not possible. Rather do:
if($request->hasfile('image'))
{
$image = $request->file('image');
$image->move($path, $photo);
}

Laravel request validation on array

Lets say I submit this form:
<form>
<input type="text" name="emails[]">
<input type="text" name="emails[]">
<input type="text" name="emails[]">
<input type="text" name="emails[]">
<input type="text" name="emails[]">
</form>
How do I then validate that at least one (anyone) of the $request->emails[] is filled?
I have tried this - however it does not work:
$request->validate([
'emails' => 'array|min:1',
'emails.*' => 'nullable|email',
]);
Laravel 7
Try this
$request->validate([
'emails' => 'array|required',
'emails.*' => 'email',
]);
Cordially
To meet your requirement, you may need custom rule
First create a rule, php artisan make:rule YourRuleName
inside YourRuleName.php
public function passes($attribute, $value)
{
foreach(request()->{$attribute} as $email) {
// if not null, then just return true.
// its assume in arrays some item have values
if ($email) { // use your own LOGIC here
return true;
}
}
return false;
}
Then,
$request->validate([
'emails' => [new YourRuleName],
]);

set rules for array input field in Yii

I have field where I can add multiple row on click "+" button. But I want to set required rules in Yii validator form.
['input_field_name', 'each', 'rule' => ['required']]
I have this input field
<input type="number" class="form-control reqInput input-unchanged" name="Domains[input_name][0][phone]">
<input type="number" class="form-control reqInput input-unchanged" name="Domains[input_name][1][phone]" value="">
<input type="number" class="form-control reqInput input-unchanged" name="Domains[input_name][2][phone]" value="">
I want required rules for each input field.
You can create your own validator for this.
in rules()
return [
// an inline validator defined as the model method validateCountry()
['country', 'validateCountry'],
];
add new function in your model:
public function validateCountry($attribute, $params, $validator)
{
//create you custom logic here, loop throughout an array and check the
//values, the code below is just example
if (!in_array($this->$attribute, ['USA', 'Indonesia'])) {
$this->addError($attribute, 'The country must be either "USA" or
"Indonesia".');
}
}

how to validated to enter numbers only and show alert message when special charter entered

I want to validate input filed which allow entering numbers only and if numeric, alphabet or copy paste not allowed and show the alert message.
<input id="amount" name="amount" type="text" placeholder="Amount" class="form-control"></div>
This my input field.
I search on google but not getting a proper answer.
From the client side you might want to create an input that already validates, to prevent unnecissary requests
<input type="text" name="amount" pattern="[0-9]*" title="Numbers only">
or
<input type="number" name="amount" title="Numbers only">
Next you want to validate the same on the server, to protect your request.
public function store(Request $request)
{
$validatedData = $request->validate([
'amount' => 'required|nummeric',
]);
// do something with amount
}
Do a server side validation as below
In your model
public static function rules()
{
return [
'amount' => ['required','numeric'],
];
}
In your controller write below code
$validator = Validator::make($request->all(), Your ModelName::rules());
if ($validator->fails()){
//display error msg
}

How to use a translation of the label to display an error, instead of the label's name, when registering a user?

When registering a new user, I use a RegisterFormRequest from Laravel.
How can I use the label name translations to display correctly the error message ?
Here is my html code,
<div>
<label for="password">
{{ Lang::get('form.password') }} *
</label>
<input name="password" type="password" required>
</div>
<div>
<label for="password_confirmation">
{{ Lang::get('form.password.confirm') }} *
</label>
<input name="password_confirmation" type="password" class="form-control" required>
</div>
Here is what is displayed. Note that the input field's "password" is used as is, but not any translations.
in the Http\Controllers\YourController.php
public function postRegister(RegisterFormRequest $request)
{
$validator = $this->registrar->validator($request->all());
$validator = $validator->setAttributeNames( [
'password' => 'My Password Name'
] );
will do the trick.
As #ali as implied, it might be better to put these values into your request class (it is where you can put the specific rules, so why not the specific label translation?).
in the Http\Controllers\YourController.php
public function postRegister(RegisterFormRequest $request)
{
$validator = $this->registrar->validator($request->all());
$validator = $validator->setAttributeNames( $request->messages() );
in the Http\Requests\RegisterFormRequest.php
public function messages()
{
return [
'password' => Lang::get('form.password'),
Laravel validation attributes "nice names"
And (as #mohamed-kawsara mentionned) in
resources/lang/de/validation.php
return [
...
"confirmed" => "The :attribute confirmation does not match.",
...
What you need is custom message in you request class.
Write this function in your request class.
public function messages()
{
return [
'password.required' => 'YOUR CUSTOM MESSAGE FOR PASSWORD REQUIREMENT'
];
}

Resources