Laravel, adding data to database after verifying ReCaptcha - laravel

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.

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

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

dd($request->country_flag); returns null in laravel

This is my form to upload a file:
<div class="col-lg-6 col-lg-offset-3">
<form method="post" action="{{ route('admin.country.store') }}" enctype="multipart/form-data">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label for="country_id">Country ID</label>
<input type="number" class="form-control" id="country_id" name="country_id">
</div>
<div class="form-group">
<label for="country_name">Country name</label>
<input class="form-control" type="text" id="country_name" name="country_name">
<p class="danger">{{ $errors->first('country_name') }}</p>
</div>
<div class="form-group">
<label for="alternate_title">Alternate Title</label>
<input class="form-control" type="text" id="alternate_title" name="alternate_title">
<p class="danger">{{ $errors->first('alternate_title') }}</p>
</div>
<div class="form-group">
<label for="country_flag">Country Flag</label>
<input class="" type="file" id="country_flag" name="country_flag">
<p class="danger">{{ $errors->first('country_flag') }}</p>
</div>
<div class="btn-group" role="group">
<button class="btn btn-default" type="reset">Reset</button>
<button class="btn btn-success" type="submit">Upload</button>
</div>
</form>
This is a function in my controller to handle form request.
public function store(Request $request)
{
$new_country = new SelectCountry();
$message = [
'required' => "This field can not be empty",
];
$this->validate($request, [
'country_name' => 'required',
'alternate_title' => 'required',
'country_flag' => 'required',
], $message);
dd($request->country_flag);
}
When I do dd($request->country_flag);, it returns null. It seems like file is not uploaded by the form.
What am I doing wrong?
I'm not sure if you can or not access a file like you are doing. Try this:
$file = $request->file('country_flas');
Try this
$input = $request->all();
$file = $input['country_flag'];
dd($file);

Octobercms successful mail send returns empty alert

I am a newbie to Laravel and OctoberCMS.
I have successfully set up an info request form that sends me an email via Mailgun when submitted. Submission is handled by an AJAX handler.
The problem I have is that the process opens an alert box with an empty array on the form page.
Here is the page: http://imageweaversmarketing.com/
Click on 'CONTACT' in the top-right to move to the form.
Here is the partial with the form:
<div class="row">
<div class="col-lg-12">
<form data-request="onInfoRequest" name="sentMessage" id="contactForm" novalidate="">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="text" class="form-control" placeholder="Your Name *" id="name" required="" data-validation-required-message="Please enter your name.">
<p class="help-block text-danger"></p>
</div>
<div class="form-group">
<input type="email" class="form-control" placeholder="Your Email *" id="email" required="" data-validation-required-message="Please enter your email address.">
<p class="help-block text-danger"></p>
</div>
<div class="form-group">
<input type="tel" class="form-control" placeholder="Your Phone *" id="phone" required="" data-validation-required-message="Please enter your phone number.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<textarea class="form-control" placeholder="Your Message *" id="message" required="" data-validation-required-message="Please enter a message."></textarea>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="clearfix"></div>
<div class="col-lg-12 text-center">
<div id="success"></div>
<button type="submit" class="btn btn-xl">
Send Message
</button>
</div>
</div>
</form>
</div>
Here is the PHP AJAX:
use Illuminate\Support\Facades\Mail;
public function onInfoRequest() {
$data = ['name' => 'test from function'];
Mail::send('mail.inforequest', $data, function ($message) {
$message->to('fake#hidden.com', 'Roger Creasy');
});
}
I appreciate any help.
I see you haven't used the data-request-success handler. That's necessary to show the output when mail is successful. Here's how I do it
function onSend()
{
// Collect input
$name = post('name');
$email = post('email');
// Form Validation
$validator = Validator::make(
[
'name' => $name,
'email' => $email
],
[
'name' => 'required',
'email' => 'required|email'
]
);
if ($validator->fails())
{
$messages = $validator->messages();
throw new ApplicationException($messages->first());
}
// All is well -- Submit form
$to = System\Models\MailSettings::get('sender_email');
$params = compact('name','email');
Mail::sendTo($to, 'temp.website::mail.newrequest', $params);
return true;
}
And on the form side I used
<form class="form-horizontal" data-request="onSend" data-request-success="alert('We have recieved your email.. we\'ll get back to you shortly')">
<div class="form-group">
<label class="col-md-4 control-label" for="name">Name</label>
<div class="col-md-5">
<input id="name" name="name" type="text" placeholder="Name" class="form-control input-md" required="">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="email">Email</label>
<div class="col-md-5">
<input id="email" name="email" type="text" placeholder="Email ID" class="form-control input-md" required="">
</div>
</div>
</form>
So basically all you need is to add a data-request-success for it to work. Enjoy!
I had to get this completed. So, I gave up on a solution within October.
I am posting what I did as a workaround, in case it is helpful to someone else.
What I did is create a route resource, and direct it to a controller to handle the form. basically I went to the Laravel base structure and handled the form through its MVC.

Resources