Laravel couldn't validate my correct form - laravel

in Laravel and my web application i have a simple form which i pasted below line:
<form class="form-horizontal" action="{{url('/addToContactUs')}}" method="POST">
#csrf
<div class="form-group required">
<label class="col-md-2 col-sm-3 control-label" for="name">Your Name</label>
<div class="col-md-10 col-sm-9">
<input type="text" name="name" value="{{old('name')}}" class="form-control"/>
</div>
</div>
<div class="form-group required">
<label class="col-md-2 col-sm-3 control-label" for="email">Your Email</label>
<div class="col-md-10 col-sm-9">
<input type="text" name="email" value="{{old('email')}}" class="form-control"/>
</div>
</div>
<div class="form-group required">
<label class="col-md-2 col-sm-3 control-label" for="enquiry">Your Enquiry</label>
<div class="col-md-10 col-sm-9">
<textarea name="enquiry" rows="10" class="form-control">{{old('enquiry')}}</textarea>
</div>
</div>
<div class="buttons">
<div class="pull-left">
<input class="btn btn-primary" type="submit" value="SUBMIT"/>
</div>
</div>
</form>
when i try to validate form fields, i get this error:
array:3 [▼
1 => array:1 [▼
0 => "The 1 field is required."
]
3 => array:1 [▼
0 => "The 3 field is required."
]
5 => array:1 [▼
0 => "The 5 field is required."
]
]
and when i try to log $request i have:
array:4 [▼
"_token" => "W8xPG039mlT0WGs0kw9lWV0FivYxKSx4XHg6LPkQ"
"name" => "this is my name"
"email" => "hello#gmail.com"
"enquiry" => "hello hello hello hello hello hello "
]
it seems all implementations are correct and i don't know why i get this error.
route for submitting this form:
Route::post('/addToContactUs', 'HomeController#addToContactUs');
and controller action:
public function addToContactUs(Request $request)
{
$validator = Validator::make(
$request->all(),
[
'name', 'required|string|min:5|max:191',
'email', 'required|string|min:5|max:191|email',
'enquiry', 'required|string|min:5',
]
);
if ($validator->fails()) {
dd($validator->errors()->messages(),$request->all());
}
}

After seeing your full validation method again & again, I got the error here, 'name', 'required… it will be 'name' => 'required…. Its just a typo, so your code will be :
$validator = Validator::make(
$request->all(),
[
'name' => 'required|string|min:5|max:191',
'email' => 'required|string|min:5|max:191|email',
'enquiry' => 'required|string|min:5',
]
);

Related

How to Retain same value entered in input fields after laravel validation fails

My Blade File Code :-
<div class="col-md-6">
<div class="form-group">
<label for="city">Assigned Hour<span class="text-danger">*</span></label>
<div class="dateBox">
<input type="number" name="assigned_hour[[]" class="form-control newAssignedHour" autocomplete="off" value="" required>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="city">Consumed Hour<span class="text-danger">*</span></label>
<div class="dateBox">
<input type="number" name="consumed_hours[[]" class="form-control newConsumedHour" autocomplete="off" value="" required>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group c-label datepicker-wrap">
<label for="city">Date<span class="text-danger">*</span></label>
<div class="dateBox">
<input type="text" name="date[]" class="form-control input-daterange newDate" id="dateInput" autocomplete="off" value="" required>
<span href="" class="dateCalender emp-cost-i">
<i class="fa fa-calendar"></i> </span>
</div>
</div>
</div>
my Controller :-
$valid = request()->validate([
'project_id' => 'required|int|exists:projects,project_id',
'email_id' => 'required|email',
'emp_id' => 'required|int|exists:contacts,employee_id',
'project_name' => 'required|string|exists:projects,name',
'GMWO' => 'required',
'employee_name' => 'required|string',
'newJobIds' => 'required|array',
'newJobNames' => 'required|array',
'newAssignedHours' => 'required|array',
'newConsumedHours' => 'required|array',
'newDates' => 'required|array'
]);
Can Anyone Suggest How to Retain the old Value for these fields. {{ old('field_name') }} that doesn't work for this.
thanks in Advance
Please try with the below method when validation gets failed and is redirected to form in the controller
->withInput()
For more reference see the below link
https://laravel.com/docs/9.x/responses#redirecting-with-input

Laravel, adding data to database after verifying ReCaptcha

I'm using ReCaptcha in my Laravel project, done it with this
tutorial.
I need to create a page where user can post his message after checking captcha.
I have created a modal dialog where user can fill in data like this :
<form class="form-horizontal" action="" method="post">
<div class="form-group error">
<label for="messageName" class="col-sm-3 control-label">Name</label>
<div class="col-sm-9">
<input type="text" class="form-control has-error" id="name" name="name" placeholder="Your name" value=""
ng-model="message.name" ng-required="true">
<span class="help-inline"
ng-show="GBM.text.$invalid && GBM.text.$touched">Required</span>
</div>
</div>
<div class="form-group error">
<label for="messageEmail" class="col-sm-3 control-label">Email</label>
<div class="col-sm-9">
<input type="email" class="form-control has-error" id="email" name="email" placeholder="E-mail" value=""
ng-model="message.email" ng-required="true">
<span class="help-inline"
ng-show="GBM.email.$invalid && GBM.email.$touched">Required</span>
</div>
</div>
<div class="form-group error">
<label for="messageLink" class="col-sm-3 control-label">Web</label>
<div class="col-sm-9">
<input class="form-control" rows="3" class="form-control has-error" id="web" name="web" placeholder="Link for your web" value="" ng-model="message.web" ng-required="false" >
</div>
</div>
<div class="form-group error">
<label for="messageText" class="col-sm-3 control-label">Comment</label>
<div class="col-sm-9">
<textarea class="form-control" rows="3" class="form-control has-error" id="comment" name="comment" placeholder="Your comment" value="" ng-model="message.text" ng-required="true" ></textarea>
<span class="help-inline"
ng-show="GBM.text.$invalid && GBM.text.$touched">Required</span>
</div>
</div>
{!! csrf_field() !!}
<!-- recaptcha -->
{{Request::is('contactd')}}
<div class="form-group">
<div class="col-md-9">
<div class="g-recaptcha" data-sitekey="{{env('GOOGLE_RECAPTCHA_KEY')}}"></div>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-9 control-label"></label>
<div class="col-md-9">
<button type="submit" name="send" class="btn btn-primary btn-lg btn-block">Add new message <span class="fa fa-paper-plane-o"></span></button>
</div>
</div>
</form>
For a route I got it like this:Route::post('contact','ContactController#store');
And here is the problem, in my controller i got this code to verify captcha:
public function store(ReCaptchataTestFormRequest $request){
return "Captcha done right! ";}
And this code to save data to database
public function store(Request $request)
{
$this->validate($request, [ 'name' => 'required|max:255' ]);
$this->validate($request, [ 'email' => 'required | email' ]);
$this->validate($request, [ 'comment' => 'required' ]);
$ip = $_SERVER['REMOTE_ADDR'];
$browser = $_SERVER['HTTP_USER_AGENT'];
$guestbook = Guest_books::create([
'name' => $request->input('name'),
'email' => $request->input('email'),
'web' => $request->input('web'),
'comment' => $request->input('comment'),
'ip' => $ip,
'browser' => $browser
]);
return $guestbook;
}
So the question is: What to write in Controller for project to verify Captcha and then post it to database?
The tutorial you've followed teaches you how to create a custom validation rule which you can then use when validating requests, either through a Form Request or directly in your controller.
The mistake you've made in your controller is that you've called validate multiple times, instead you should pass it an array containing all of your rules, including your recaptcha rule, e.g:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|max:255',
'email' => 'required|email',
'comment' => 'required',
'g-recaptcha-response' => 'required|recaptcha',
]);
// ...
}
Additionally, you should note that the store method should always return a redirect.

make certain creation between form and field in database in laravel

want to produce data exclusive to some field in database, so i add them in my view create . but there is an error cannot be null. even though the field is nullable.
this my view form.blade.php
<form action="" method="POST">
#csrf
<div class="box-body">
<div class="form-group">
<label for="">Project *</label>
<select class="form-control select2" style="width: 100%;" name="project_id">
<option>Select One</option>
#foreach($projects as $id => $project)
<option value="{{$id}}">{{$project}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="">Story # Meeting Name *</label>
<input type="text" class="form-control" name="user_story">
</div>
<div class="form-group">
<label for="">Category *</label>
<select class="form-control select2" style="width: 100%;" name="task_category">
<option>Select One</option>
#foreach($task_categories as $task_category)
<option value="{{$task_category->task_category}}">{{$task_category->task_category}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="">Estimated *</label>
<input type="text" class="form-control" name="estimated_time">
</div>
</div>
<div class="box-footer">
<a href="">
<button type="submit" class="btn btn-primary col-md-12" style="border-radius : 0px;">SAVE</button>
</a>
</div>
</form>
this my request
public function rules()
{
return [
'project_id',
'task_category',
'estimated_time',
'spent_time' => 'nullable',
'user_story' => 'nullable',
'story/meeting_name' => 'nullable',
'assign' => 'nullable',
'percentage' => 'nullable',
'lateness' => 'nullable',
'index' => 'nullable',
];
}
this my controller
public function store(OngoingRequest $request)
{
// dd($request->all());
$spentime = SpentTime::create([
'project_id' => request('project_id'),
'user_story' => request ('user_story'),
'task_category' => request('task_category'),
'estimated_time' => request('estimated_time'),
'spent_time' => request('spent_time'),
'assign' => request('assign'),
'story/meeting_name' => request('story/meeting_name'),
'percentage'=> request('percentage'),
'lateness' => request('lateness'),
'index'=> request('index'),
]);
return redirect()->route('plan.index');
}
and the error :
error
fields that i don't want to fill and not in the form must be filled. but im not need that.
set spent_time filed default value other wise set a nullable value
$table->string('spent_time')->nullable();
$table->boolean('spent_time')->default(0);

getting all the data except image in laravel error

<form id="add-record" enctype="multipart/form-data">
#csrf
<div class="success">
</div>
<div class="form-group row">
<label for="name" class="col-sm-3 label-name col-form-label">Full Name</label>
<div class="col-sm-9 input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-user"></i></span>
</div>
<input type="text" class="form-control input" id="name" name="name" placeholder="Full Name">
</div>
</div>
<div class="row error">
<div class="col-sm-9 offset-sm-3">
<span class="text-danger" id="name-error"></span>
</div>
</div>
<div class="form-group row">
<label for="datepicker" class="col-sm-3 col-form-label">Date of birth</label>
<div class="col-sm-9 input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-calendar"></i></span>
</div>
<input type="text" class="form-control input" id="datepicker" name="dateofbirth" placeholder="">
</div>
</div>
<div class="row error">
<div class="col-sm-9 offset-sm-3">
<span class="text-danger" id="dateofbirth-error"></span>
</div>
</div>
<div class="form-group row">
<label for="course" class="col-sm-3 col-form-label">Gender</label>
<div class="col-sm-9 input-group">
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" id="male" value="Male" checked>
<label class="form-check-label" for="male">
Male
</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" id="female" value="Female">
<label class="form-check-label" for="female">
Female
</label>
</div>
</div>
</div>
<div class="form-group row">
<label for="address" class="col-sm-3 col-form-label">Address</label>
<div class="col-sm-9 input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-home"></i></span>
</div>
<input type="text" class="form-control input" id="address" name="address" placeholder="Address">
</div>
</div>
<div class="row error">
<div class="col-sm-9 offset-sm-3">
<span class="text-danger" id="address-error"></span>
</div>
</div>
<div class="form-group row">
<label for="email" class="col-sm-3 col-form-label">Email</label>
<div class="col-sm-9 input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-envelope"></i></span>
</div>
<input type="email" class="form-control input" id="email" name="email" placeholder="yourmail#email.com">
</div>
</div>
<div class="row error">
<div class="col-sm-9 offset-sm-3">
<span class="text-danger" id="email-error"></span>
</div>
</div>
<div class="form-group row">
<label for="phone" class="col-sm-3 col-form-label">Phone Number</label>
<div class="col-sm-9 input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-phone"></i></span>
</div>
<input type="text" class="form-control input" id="phone" name="phone" placeholder="+3784773847">
</div>
</div>
<div class="row error">
<div class="col-sm-9 offset-sm-3">
<span class="text-danger" id="phone-error"></span>
</div>
</div>
<div class="form-group row">
<label for="course" class="col-sm-3 col-form-label">Course Name</label>
<div class="col-sm-9 input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-book-open"></i></span>
</div>
<input type="text" class="form-control input" id="course" name="course" placeholder="Course name">
</div>
</div>
<div class="row error">
<div class="col-sm-9 offset-sm-3">
<span class="text-danger" id="course-error"></span>
</div>
</div>
<div class="form-group row">
<label for="image-file" class="col-sm-3 col-form-label">Your Image</label>
<div class="col-sm-9 input-group">
<input type="file" class="form-control-file input-image" name="image" id="image-file">
</div>
</div>
<div class="row error">
<div class="col-sm-9 offset-sm-3">
<span class="text-danger" id="image-error"></span>
</div>
</div>
<div class="form-group row">
<div class="col-sm-9 offset-sm-3 input-group">
<input type="submit" class="btn btn-primary">
</div>
</div>
</form>
strong text
When i dd($request->all()); in store function in controller, i get all other values but not image.. It even doesn't shows image=null when i dd(); array:8 [ "_token" => "C27oLkk8wDTcBnZDA38nPCte4SY18HqXqxcFDcrI" "name" => null "dateofbirth" => null "gender" => "Male" "address" => null "email" => null "phone" => null "course" => null ]
Iam using ajax request Although i input the image it shows the image is required.. What am i doing wrong here??
$validator = Validator::make($request->all(), [
'name' => 'required|min:2',
'dateofbirth' => 'required|date',
'gender' => 'required',
'address' => 'required',
'email' => 'required|email',
'phone' => 'required|numeric',
'course' => 'required',
'image' => 'required|image|mimes:jpeg,png,jpg',
]);
if($validator->fails()) {
return response()->json([
'errors' => $validator->errors(),
]);
}
$name = $request['name'];
$dateofbirth = $request['dateofbirth'];
$gender = $request['gender'];
$address = $request['address'];
$email = $request['email'];
$phone = $request['phone'];
$course = $request['course'];
if($request->hasFile('image')) {
$img_name = time() . '.' .$request->file('image')->getClientOriginalExtension();
$destinationPath = public_path('/assets/images/');
$request->file('image')->move($destinationPath, $img_name);
$image = $img_name;
}
Student::create([
'name' => $name,
'dateofbirth' => $dateofbirth,
'gender' => $gender,
'address' => $address,
'email' => $email,
'phone' => $phone,
'course' => $course,
'image' => $image,
]);
You can try this
$validator = Validator::make($request, [
'name' => 'required|min:2',
'dateofbirth' => 'required|date',
'gender' => 'required',
'address' => 'required',
'email' => 'required|email',
'phone' => 'required|numeric',
'course' => 'required',
'image' => 'required|file|mimetypes:image/jpeg,image/png',
]);
if($validator->fails()) {
return response()->json([
'errors' => $validator->errors(),
]);
}
//store image
$path = $request->image->store('images');
//it will store your images at `storage/app/public/images` folder with dynamically generated image name, be sure create images folder there
Student::create([
'name' => $request->name,
'dateofbirth' => $request->dateofbirth,
'gender' => $request->gender,
'address' => $request->address,
'email' => $request->email,
'phone' => $request->phone,
'course' => $request->course,
'image' => $path,
]);
Execute this command from command line
php artisan storage:link
it will create symbolic link of storage/app/public to public/storage folder.
now you can use your image in view like this
{{asset('storage/images/test.jpeg')}}
If you have to read that file in controller then you can use it like this
Storage::disk('public')->get('images/test.jpeg');
Always store your files in storage folder. All public files should be stored at storage/app/public
For details check here https://laravel.com/docs/5.6/filesystem#introduction

How to set value variable from checkbox checked laravel?

I have blade:
<div class="form-group">
<label for="exampleInputEmail1">Họ và tên</label>
<input type="text" class="form-control" id="exampleInputEmail1" placeholder="Nhập tên" name="username" value="{{old('username')}}">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Nhập địa chỉ email" name="email" value="{{old('email')}}">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Mật khẩu</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Nhập mật khẩu" name="pass1">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Nhập lại mật khẩu</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Nhập lại mật khẩu" name="pass2">
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="cbadmin" value="1" {{old('cbadmin') ? "checked" : ''}} > Admin
</label>
</div>
I want set value variable $lv =1 while checkbox "cbadmin" checked. But not know how to retrieve it. I want set default lv=0, lv=1 if checkbox checked.
public function getAdd(AddUserRequest $request)
{
User::create([
'name' => $request->username,
'email' => $request->email,
'password' => Hash::make($request->pass1),
'level' => ????
]);
return redirect('admin/manage-user/add')->with('success','Bạn đã thêm thành công!');
}
You could check whether cbadmin exists in the $request. If it exists, it was checked and then you could set $lv to 1.
$lv=isset($request['cbadmin'])?1:0;
Use input() with a default value for the case of cbadmin being unchecked:
User::create([
'name' => $request->username,
'email' => $request->email,
'password' => Hash::make($request->pass1),
'level' => (int)$request->input('cbadmin', 0)
);

Resources