Input checkbox with multiple value on laravel - laravel

I'm making input using the checkbox, only hardware table need to input multiple checkbox values
When im trying using implode, i got appear errorException: "implode(): Invalid arguments passed".
Here my controller code :
auth()->user()->Form()->create
([
'user_id' => $request->user_id,
'os' => $request->os,
'hardware' => implode(',', $request->input('hardware')),
// $arrayToString = implode(',', $request->input('hardware'));
'software' => $request->software,
'signature' => $signature,
'status_desc' => $request->status_desc,
'cancel_deskripsi' => $request->cancel_deskripsi
]);
dd($form);
return redirect()->route('form')->with('status', 'success');
My view code:
<div class="form-group col-md-12">
<label>Hardware :</label>
<div class="checkbox-list">
<label class="form-group col-md-4">
<input type="checkbox" id="hardware" name="hardware[]" value="Komputer AIO">
<span></span>
Komputer AIO
</label>
<label class="form-group col-md-4">
<input type="checkbox" class="form-group" id="hardware" name="hardware" value="Laptop">
<span></span>
Laptop
</label>
<input id="other" name="how" type="checkbox" class="form-group">
<label for="other" class="form-group">Other :</label>
<div class="other-disclosure">
<input type="text" name="hardware" id="os-other" class="form-group col-md-2" placeholder="...">
</div>
</div>
How to solve this problem ?

You probably want to have all those inputs named hardware[] (so they will all end up in an array as the input hardware) and incase nothing is passed (unchecked checkboxes) you should make sure to handle this:
'hardware' => implode(',', (array) $request->input('hardware', []));
Here if nothing is passed then $request->input('hardware', []) is [], an array. The (array) cast is just to make sure there is an array being passed to implode.

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.

How to validate this context? In the validate method()?

Context: When a user creates a new conference he needs to select a start and an end date for the conference and the user needs to enter an end date after the start date, that is, the end date needs to be after the start date.
To deal with this logic properly, do you know if we can use the laravel validate method in the store method or is not a good approach or not possible do with this method? If it is not adequate to do this in the validate method do you know how to properly do that?
ConferenceController store method:
public function store(Request $request)
{
$this->validate($request, [
'conference_name' => 'required|max:255|string',
'conference_startDate' => 'required|date_format:d/m/Y',
'conference_endDate' => 'required|date_format:d/m/Y',
]);
$conference = Conference::create([
'nome' => $request->conference_name,
'startDate' => Carbon::parse($request->conference_startDate),
'endDate' => Carbon::parse($request->conference_endDate),
]);
}
Html fields:
<div class="form-row">
<div class="form-group col-md-6">
<label for="conference_startDate">Stard Date</label>
<div class="input-group date" data-provide="datepicker">
<input type='text' onkeydown="event.preventDefault()"
name="conference_startDate" value="{{ old('conference_startDate') }}"
class="form-control" placeholder="DD/MM/YYY" />
<span class="input-group-addon"><i class="fa fa-calendar text-primary" aria-hidden="true"></i></span>
</div>
</div>
<div class="form-group col-md-6">
<label for="conference_endDate">End Date</label>
<div class="input-group date" data-provide="datepicker">
<input type='text' class="form-control"
value="{{ old('conference_endDate') }}" name="conference_endDate" placeholder="DD/MM/YYY"/>
<span class="input-group-addon"><i class="fa fa-calendar text-primary" aria-hidden="true"></i></span>
</div>
</div>
</div>
As stated in the documentation, you could use the after rule:
after:date
The field under validation must be a value after a given date. The
dates will be passed into the strtotime PHP function:
'start_date' => 'required|date|after:tomorrow'
Instead of passing a
date string to be evaluated by strtotime, you may specify another
field to compare against the date:
'finish_date' => 'required|date|after:start_date'
So in your code:
$this->validate($request, [
'conference_name' => 'required|max:255|string',
'conference_startDate' => 'required|date_format:d/m/Y',
'conference_endDate' => 'required|date_format:d/m/Y|after:conference_startDate',
]);
Also, check this similar question.
Update
To check for a date after of equal another date, as stated in the docs, you should use:
after_or_equal:date
The field under validation must be a value after
or equal to the given date. For more information, see the after rule.

PhpUnit testing, how to check a checkbox if there are multiple checkboxes with same name in a form

I am testing a form. In the form, there are some checkboxes which are with the same name as there are multiple checkboxes to select from.
So my check boxes are like this:
<div class="col-sm-10">
<div class="checkbox">
<input id="department_1" name="departments[]" type="checkbox" value="1">
<label for="department_1">Sales</label>
</div>
<div class="checkbox">
<input id="department_2" name="departments[]" type="checkbox" value="2">
<label for="department_2">Marketing</label>
</div>
<div class="checkbox">
<input id="department_3" name="departments[]" type="checkbox" value="3">
<label for="department_3">Tech Help</label>
</div>
</div>
My testing code is like this:
public function testUserCreation()
{
$this->be(User::find(10));
$this->visit('/users/create')
->type('First', 'first_name')
->type('Last', 'last_name')
->type('test#esample.com', 'email')
->type('123456', 'password')
->type('123456', 'password_confirmation')
->check('departments')
->press('Submit')
->seePageIs('/users');
}
When I am trying to check if throws error:
InvalidArgumentException: Nothing matched the filter [permissions] CSS
query provided for
If you specify the index for the multiple checkbox in both your form and test, then it works.
Form:
<input id="department_1" name="departments[0]" type="checkbox" value="1">
<input id="department_2" name="departments[1]" type="checkbox" value="2">
Unit test:
public function testUserCreation()
{
$this->be(User::find(10));
$this->visit('/users/create')
->type('First', 'first_name')
->type('Last', 'last_name')
->type('test#esample.com', 'email')
->type('123456', 'password')
->type('123456', 'password_confirmation')
->check('departments[0]')
->press('Submit')
->seePageIs('/users');
}
Using named indexes works as well.
<input name="departments[department_1]" type="checkbox" value="1">
// [...]
$this->check('departments[department_1]');
The only way I managed this was:
$this->visit('/users/create')
->submitForm('Submit', [
...
...
'departments[0]' => '1',
'departments[1]' => '2'
])
->seePageIs('/users');
Note that if you want to check the first and last item, you have to follow the order the inputs are placed.
$this->visit('/users/create')
->submitForm('Submit', [
...
...
'departments[0]' => '1',
'departments[2]' => '3' // index 2 instead 1.
])
->seePageIs('/users');

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