Livewire quantity input field not update dynamically when change value - ajax

I've purchased pos software which is not updated the quantity input field when changed into the checkout page it's working with a button. I want to change form submit button quantity input to dynamic input field with cart total, not with a hard-coded button.
Screenshot of this problem
Blade Code
<form wire:submit.prevent="updateQuantity('{{ $cart_item->rowId }}', '{{ $cart_item->id }}')">
<div class="input-group">
<input wire:model.lazy="quantity.{{ $cart_item->id }}" style="min-width: 40px;max-width: 90px;" type="number" class="form-control" value="{{ $cart_item->qty }}" min="1">
<div class="input-group-append">
<button type="submit" class="btn btn-primary">
<i class="bi bi-check"></i>
</button>
</div>
</div>
Update function
public function updateQuantity($row_id, $product_id) {
if ($this->check_quantity[$product_id] < $this->quantity[$product_id]) {
session()->flash('message', 'The requested quantity is not available in stock.');
return;
}
Cart::instance($this->cart_instance)->update($row_id, $this->quantity[$product_id]);
$cart_item = Cart::instance($this->cart_instance)->get($row_id);
Cart::instance($this->cart_instance)->update($row_id, [
'options' => [
'sub_total' => $cart_item->price * $cart_item->qty,
'code' => $cart_item->options->code,
'stock' => $cart_item->options->stock,
'unit' => $cart_item->options->unit,
'product_tax' => $cart_item->options->product_tax,
'unit_price' => $cart_item->options->unit_price,
'product_discount' => $cart_item->options->product_discount,
'product_discount_type' => $cart_item->options->product_discount_type,
]
]);
}

Related

Laravel Livewire using flatpickr

Im trying to make us of the flatpickr event onMonthChange but using via a Livewire method.
I am using the answer from this - How to make flatpickr datepicker reactive in livewire / alpinejs app?
But having trouble knowing how to trigger the onMonthChange js event then running livewire method.
views/components/flatpickr.blade.php
#props(['options'])
<div wire:ignore>
<input
x-data="{value: #entangle($attributes->wire('model')), instance: undefined}"
x-init="() => {
$watch('value', value => instance.setDate(value, true));
instance = flatpickr($refs.input, {{ json_encode((object)$options) }});
}"
x-ref="input"
x-bind:value="value"
type="text"
{{ $attributes->merge(['class' => 'form-input w-full rounded-md shadow-sm']) }}
/>
</div>
views/livewire/booking-search.blade.php
<div class="col-span-6 sm:col-span-3">
<label for="datePicker" class="block text-sm text-gray-700 font-semibold">Select Date</label>
<x-flatpickr id="flatpickr_operation_date" wire:model="selectedDate" :options="$options"/>
</div>
app/Http/Livewire/BookingSearch.php
class BookingSearch extends Component
{
public $selectedDate;
public $selectedMonth
public $options = [
'minDate' => 'today',
'maxDate' => "2022-05-31",
'inline' => true,
'monthSelectorType' => 'static',
'dateFormat' => 'd-m-Y',
'enableTime' => false,
'altFormat' => 'j F Y',
'altInput' => true,
];
public function updatedSelectedMonth() {
dd('foo');
}
So im trying to get updatedSelectedMonth to run when the month is changed but because its not a input it self, just not sure how to get livewire to fire on the change.
Sorry JS isnt my strongest

production.ERROR: InvalidArgumentException: Data missing in Laravel

I am working on a project in Laravel-5.8. I have this in my model:
Model:
protected $fillable = [
'id',
'email',
'hire_date',
'first_name',
'other_name',
'last_name',
'date_of_birth',
];
protected $dates = [
'date_of_birth',
'hire_date',
];
public function setDateOfBirthAttribute($value)
{
$this->attributes['date_of_birth'] = Carbon::createFromFormat('d-m-Y', $value);
}
public function setHireDateAttribute($value)
{
$this->attributes['hire_date'] = Carbon::createFromFormat('d-m-Y', $value);
}
Then this is my controller.
Controller:
$arr = [
'first_name' => $request->first_name,
'last_name' => $request->last_name,
'hire_date' => $request->hire_date,
'date_of_birth' => $request->date_of_birth,
'other_name' => $request->other_name,
];
$employee = HrEmployee::create($arr);
I use JQuery datepicker:
< script type = "text/javascript" >
$(function() {
$('.birthDate').datepicker({
dateFormat: 'dd-mm-yy',
changeMonth: true,
changeYear: true,
maxDate: -1,
showAnim: 'slideDown',
duration: 'fast',
});
}); <
/script>
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> Date of Birth:</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="far fa-calendar-alt"></i></span>
</div>
<input type="text" placeholder="dd/mm/yyyy" readonly autocomplete="off" name="date_of_birth" value="{{ old(" date_of_birth} ") }}" class="form-control birthDate">
</div>
</div>
<!-- /.form-group -->
</div>
When I submitted the form, I got this error:
[2021-02-12 12:50:07] production.ERROR: InvalidArgumentException: Data missing in /var/www/html/peopleedgeapp/vendor/nesbot/carbon/src/Carbon/Traits/Creator.php:623
Stack trace:
#0 /var/www/html/myapp/vendor/nesbot/carbon/src/Carbon/Traits/Creator.php(645): Carbon\Carbon::rawCreateFromFormat('d-m-Y', NULL, NULL)
#1 /var/www/html/myapp/app/Models/Hr/HrEmployee.php(156): Carbon\Carbon::createFromFormat('d-m-Y', NULL)
#2 /var/www/html/myapp/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php(615): App\Models\Hr\HrEmployee->setDateOfBirthAttribute(NULL)
#3 /var/www/html/myapp/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php(569): Illuminate\Database\Eloquent\Model->setMutatedAttributeValue('date_of_birth', NULL)
#4 /var/www/html/myapp/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(329): Illuminate\Database\Eloquent\Model->setAttribute('date_of_birth', NULL)
Where did I get it wrong? The same error occur for hire_date.
How do I get this resolved?
Thanks
Hard to say what's exactly wrong but for sure there is a problem here:
value="{{ old(" date_of_birth} ") }}"
It should be rather:
value="{{ old('date_of_birth') }}"
First of all set attribute methods are not used for guarded fields.
They have completely different perpouse.
Secondary, according to your error log somehow your setters were triggered with NULL passing instead of parameters, where parameters are required which is also wrong.
So where your setters triggered that is the question I think.

How to define an onclick function on Laravel Collectives?

I have implemented a drop down using Laravel collectives. I need to call function setMaterialValue(let x){ console.log(x)} on each time I select a material. This should be specific to each material as cotton-10, wetlook-20, crocodile-30 etc. Without Laravel collective this can be performed as
<option onclick="setMaterialValue(10);">Cotton</option>
How to perform this using Laravel collectives?
My code is as follows:
<div class="card">
<div class="card-header"><h2 class="card-title m-0">Feature Selector</h2></div>
<div class="card-body">
<h5 class="card-title"><b>Material Selector</b></h5>
<div class="row">
<div class="col-md-6">
Textile Material
</div>
<div class="col-md-6">
{{Form::select('material_selector', [
'10' => 'Cotton',
'20' => 'Wet Look',
'30' => 'Crocodile',
], null, ['placeholder' => 'Select Material'],['class'=>'form-control'])
}}
</div>
</div>
<hr>
</div>
</div>
FYI - Where your class declaration is add it and any other html attributes there as well:
{{ Form::select('material_selector',
[
'1' => 'Cotton',
'2' => 'Wet Look',
'3' => 'Crocodile',
],
null,
['placeholder' => 'Select Material'],
[
'class'=>'form-control',
'onclick'=>'setMaterialValue(10)' // <== ADD IT HERE
])
}}
You should probably use jQuery. Then you can address your select element as follows
$(document).ready(function() {
$('.form-control[name="material_selector"]').on('change', showSelectedValue);
function showSelectedValue(event) {
var target = $(event.target);
console.log(target.val() + " = " + target.find('option:selected').text());
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="material_selector" class="form-control">
<option value="10">Cotton</option>
<option value="20">Wet Look</option>
<option value="30">Crocodile</option>
</select>
Another option
If you really do not want to use jQuery, then try to use the onChange attribute for the select tag like the example below
{{Form::select(
'material_selector', // name attribute of the select
['10' => 'Cotton', '20' => 'Wet Look', '30' => 'Crocodile'], // option values
null, // selected value, for example '20'
['placeholder' => 'Select Material', 'class' => 'form-control', 'onChange' => 'showSelectedValue(this)'], // attributes for <select>
)}}
function showSelectedValue(element) {
console.log(element.value + " = " + element.options[element.selectedIndex].text);
}
<select name="material_selector" class="form-control" onChange="showSelectedValue(this)">
<option value="10">Cotton</option>
<option value="20">Wet Look</option>
<option value="30">Crocodile</option>
</select>

Problems with Laravel Pivot Table

I am working on a medical lab application in laravel where I have the following tables:
1. Test table: This is a table which stores all the information related to medical tests:
2: Checkup: This is a page which contains all the patient information along with the tests he/she takes.
This is the test page:
This is the Checkup page where the tests and their results are selected:
Here can be many tests and user can check any number of them and will write the result of the test in the textfield below the checkbox.
I get this data in the controller like below code and save it to the database:
$this->validate($request,
[
'patient_name' => 'required|max:50',
'patient_age' => 'required',
'gender' => 'required',
'patient_type' => 'required',
'technition_id' => 'required',
'result' => 'required',
'test' => 'required',
'amount' => 'required'
]);
if( ($request->patient_type == 2) && ($request->doctor_id==0) )
{
return redirect()->back()->withInput(Input::all())->withErrors(['message' => 'Please select a valid Doctor.']);
}
$checkup = new Checkup;
$checkup->patient_name = $request->patient_name;
$checkup->patient_age = $request->patient_age;
$checkup->gender = $request->gender;
$checkup->patienttype_id = $request->patient_type;
$checkup->technition_id = $request->technition_id;
if(isset($request->doctor_id))
{
$checkup->doctor_id = $request->doctor_id;
}
$checkup->amount = $request->amount;
// $checkup->result = $request->result;
$checkup->save();
$tests =[];
$tests = $request->test;
$results =[];
$results = $request->result;
//$checkup->tests()->attach($tests->id, ['result' => $result]);
$sync_data = [];
for($i = 0; $i < count($tests); $i++)
$sync_data[$tests[$i]] = ['result' => $results[$i]];
$checkup->tests()->sync($sync_data);
Session::flash('success', 'The record was successfully saved.');
return redirect()->route('checkups.index');
Now the problem is that when I check all the checkboxes and write the result of all the tests then it is fine but when I select some and leave some of them then it gives error and the error comes because the result textbox for the unchecked test is empty.
This is the case when I select one test and leave the others:
When I check on test and write the result of it and then var_dump both test and result arrays i get the below output:
In the above image we can see that the test array contains one item because only one checkbox was checked but the result array contains two items and the first one is NULL which belongs to the unchecked checkbox.
This is the view file of the checkboxes and the textfields:
{{ Form::label('tests', 'Tests Taken') }}
#foreach(App\Test::all() as $test)
<div class="checkbox checkbox-switchery">
{{ Form::label('test', $test->name) }}
<input name="test[]" value="{{ $test->id }}" type="checkbox" class="switchery-primary">
</div>
<div>
{{ Form::label('result', "Result") }}
<input name="result[]" type="text" class="form-control">
</div>
#endforeach
<div class="form-group">
{{ Form::label('amount', 'Amount') }}
{{ Form::text('amount', null, ['class' => 'form-control']) }}
</div>
<div class="form-group">
{{Form::button('<i class="fa fa-save"> Save</i>', ['type' => 'submit', 'class' => 'btn btn-success'])}}
</div>
{!! Form::close() !!}
Please help me on this and show me how to insert the pivot table data properly to the system.
Thanks in advance for any help.
Try this..
In your blade file :
#foreach(App\Test::all() as $index => $test)
<div class="checkbox checkbox-switchery">
{{ Form::label('test', $test->name) }}
<input name="test[{{ $index }}]" value="{{ $test->id }}" type="checkbox" class="switchery-primary">
</div>
<div>
{{ Form::label('result', "Result") }}
<input name="result[{{ $index }}]" type="text" class="form-control">
</div>
#endforeach
Instead of the for loop you can use foreach lopp.
$sync_data = [];
foreach($tests as $index => $value) {
if(!empty($results[$index]) {
$sync_data[$value] = ['result' => $results[$index]]
}
}
$checkup->tests()->sync($sync_data);

Get Model and id of the Model you are adding a note to

Basically,
I have a notes table with a polymorphic relationship with videos and users and want to determine how on my store method in my NotesController I get which model I am added a note to, and the id in that table. This is my create query on my store method
$note = Note::query()->create([
'body' => $request->get('body'),
'user_id' => \Auth::id(),
'noteable_id' => 1, **(needs to be dynamic)**
'noteable_type' => Video::class, **(needs to be dynamic)**
]);
Blade
<form action="{{route('admin.note.store'}}" method="post">
{{csrf_field()}}
<div class="input-group">
<input id="btn-input" name="body" required="true" type="text" class="form-control input-sm" placeholder="Type your message here...">
<span class="input-group-btn">
<button type="submit" class="btn btn-warning btn-sm" id="btn-chat">
Submit
</button>
</span>
</div>
</form>
Essentially I want to know how I can retrieve the noteable_type = (Model I'm updating) and the noteable_id (id of the record I'm adding a note to)
Is there any way of retrieving this dynamically on the request?
Thanks
You need to get the video or any other model some way. If your route contains the video id then you can use that in your controller. Here are some ways you can do this.
//Get your video model
$video = Video::find(...);
$note = \Auth::user()->create([
'body' => $request->get('body'),
'noteable_id' => $video->id,
'noteable_type' => get_class($video),
]);
// OR
$note = new Note([
'body' => $request->get('body'),
'user_id' => \Auth::id(),
]);
$video->note()->save($note);
Run php artisan route:list and post it so that i can advise you on how to fetch the model.

Resources