Auto calculate total value laravel livewire - php

i have a problem where the value isn't calculated.
I have function where the user able to update Weight/size and quantity(if the input isn't in readonly). When the user enter a new weight/size it will be auto-calculated in the Order Total. Apparently, there is a value already in the Order Total (since it is an update) so i want it to auto update the value in the order total when the user update the new input in weight/size or quantity.
pls click this picture
here is my updates.blade.php
<div class="col-sm-12 col-md-6" >
<div class="card">
<div class="card-body">
<div class="form-actions">
<div class="container" style="padding: 0;margin: 0;">
<div class="row">
<div class="col-sm-6" >
<span class="float-sm-left">
<h3 class="card-title">Update Order</h3>
</span>
</div>
</div>
</div>
</div>
</br>
<form action="" method="POST" >
#csrf
#method('PUT')
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="validationTooltip01">Order ID</label>
<input type="text" class="form-control" wire:model="orderID" value="" readonly>
</div>
<div class="col-md-4 mb-3">
<label for="validationTooltip02">Order Date</label>
<input type="text" class="form-control" wire:model="orderDate" value="" readonly>
</div>
<div class="col-md-4 mb-3">
<label for="validationTooltipUsername">Order Status</label>
<input type="text" class="form-control" wire:model="orderStatus" value="" readonly>
</div>
</div>
<div class="form-row">
<div class="col-md-6 mb-3">
<label class="form-control-label" >Customer Phone Number</label>
<input type="text" name="" value="" class="form-control" maxlength="11" wire:model="custPhone" readonly>
</div>
<div class="col-md-6 mb-3">
<label class="form-control-label" >Customer Name</label>
<input type="text" name="" value="" class="form-control" maxlength="11" wire:model="custName" readonly>
</div>
</div>
<div class="form-row">
#foreach($serviceOrder as $o)
<div class="col-md-5 mb-3">
<label class="form-control-label" >Service {{ $loop->iteration }} </label>
<input type="text" wire:model="serviceOrder.{{ $loop->index }}.serv.serviceName" class="form-control " readonly>
</div>
<input type="hidden" wire:model="serviceOrder.{{ $loop->index }}.serv.servicePrice" class="form-control col-sm-1 mb-3" readonly>
<div class="col-md-3 mb-3">
<label class="form-control-label" >Weight/Size</label>
<input type="text" name="" value="" wire:model="serviceOrder.{{ $loop->index }}.weightsize" class="form-control">
</div>
<div class="col-md-3 mb-3">
<label class="form-control-label" >Quantity*opt</label>
<input type="text" name="" value="" wire:model="serviceOrder.{{ $loop->index }}.quantity" class="form-control" #if(!$serviceOrder[$loop->index]['quantity']) readonly #endif >
</div>
#endforeach
</div>
<label class="form-control-label" >Order Total RM</label>
<input type="number" wire:model="orderTotal" value="" class="form-control" readonly>
</br>
<div class="form-actions">
<div class="container" style="padding: 0;margin: 0;">
<div class="row">
<div class="col-sm-6" >
<span class="float-sm-left">
<a class="btn btn-primary" href="{{ route('orders.indexInProcess') }}"> Back</a>
</span>
</div>
<div class="col-sm-6">
<span class="float-sm-right">
<div class="text-right">
<button type="submit" class="btn btn-info mr-2">Update</button>
<button type="reset" class="btn btn-dark float-right">Reset</button>
</div>
</span>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
here is the livewire updates.php
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Customer;
use App\Service;
use App\Order;
use App\ServiceOrder;
class Updates extends Component
{
public $orders;
public $orderID;
public $orderDate;
public $orderStatus;
public $orderTotal;
public $custName;
public $custPhone;
public $serviceName;
public $servicePrice;
public $weightsize;
public $quantity;
public $serviceOrder;
public function mount($order,$so)
{
//$orders = Order::with('customer')->get();
//ServiceOrder::with('serv')->where('order_id', $order->id)->get();
$this->orderID = $order->id;
$this->orderDate = $order->orderDate;
$this->orderStatus = $order->orderStatus;
$this->orderTotal = $order->orderTotal;
$this->custPhone = $order->customer->custPhone;
$this->custName = $order->customer->custName;
$this->serviceOrder = $so->toArray();
//dd($this->serviceOrder);
//$so->serviceName,
//$so->weightsize,
//$so->quantity
}
public function render()
{
//$so = ServiceOrder::with('serv')->where('order_id', $order->id)->get();
return view('livewire.updates');
}
public function updatedInputs($name)
{
$array = explode('.', $name);
if ($array[1] == 'serviceName') {
$this->inputs[$array[0]]['servicePrice'] = $this->services->find($value)->servicePrice;
}
try {
$this->calculateTotal();
} catch (\Exception $e) {
}
}
// perform calculation here.
public function calculateTotal(){
$this->orderTotal = $this->orderTotal;
foreach ($this->serviceOrder as $item) {
if($item['quantity'] == ''){
$item['optQuantity']= 1;
$this->orderTotal += ($item['servicePrice'] * $item['weightsize']) * ($item['quantity']);
}else{
$this->orderTotal += $item['servicePrice'] * ($item['weightsize']) * ($item['quantity']);
}
//$this->total *= $item['optQuantity']; // * price;
}
}
}
please help me out here T.T

You can fire event from component (for example) and then register listener in class and call a method for updating total. Check documentation for that.

"Apparently, there is a value already in the Order Total (since it is an update) so i want it to auto update the value in the order total when the user update the new input in weight/size or quantity."
So, the problem is $orderTotal only update once? it doesn't update when user update new input?. Livewire should render everytime there is action or any input.
First of all, i advice u to check what happen when to your function when user update the new input with dd function.
public function calculateTotal(){
dd('is this func work?');
$this->orderTotal = $this->orderTotal;
foreach ($this->serviceOrder as $item) {
if($item['quantity'] == ''){
$item['optQuantity']= 1;
$this->orderTotal += ($item['servicePrice'] * $item['weightsize']) * ($item['quantity']);
}else{
$this->orderTotal += $item['servicePrice'] * ($item['weightsize']) * ($item['quantity']);
}
//$this->total *= $item['optQuantity']; // * price;
}
}
After you debug your function, maybe you already found the answer you looking for or you can come back and ask me anything. ^^

Related

I want to update values in two tables

I created an edit form to update values in my database and then show it on the main page. The problem is that it doesn't save the data to DB.
the request passes: Status Code: 302 Found
with all the values that I want to change (for example adding phone and mail):
effective_date_practitioner: 2019-01-01
expiry_date_practitioner:
phone_number_practitioner: 918273645
mobile_number_practitioner:
email_practitioner: test#test.pl
practitioner_specialty_id_update: 1
effective_date_specialty: 2019-01-01
expiry_date_specialty:
Edit blade
<div class="edit-practitioner" style="display: none;">
<form style="box-shadow: none;" action="/practitioner/update/{{$practitioner->practitioner_id}}" method="post"
class="j-pro" id="update-practitioner-form">
#csrf
<div class="j-content">
<div id="j-row-id" class="j-row">
<div class="row">
<div class="col-sm-12 col-lg-12 col-xl-5">
<div class=" j-unit">
<div class="j-divider-text j-gap-top-20 j-gap-bottom-45">
<span>Practitioner Information</span>
</div>
<label class="j-label">{{trans('personalData.effectiveDate')}}</label>
<div class="j-input">
<input type="date" value="{{$practitioner->effective_date}}"
name="effective_date_practitioner">
</div>
<label class="j-label">{{trans('personalData.expiryDate')}}</label>
<div class="j-input">
<input type="date" value="{{$practitioner->expiry_date}}"
name="expiry_date_practitioner">
</div>
<label class="j-label">{{trans('personalData.phoneNumber')}}</label>
<div class="j-input">
</label>
<input type="tel" value="{{$practitioner->phone}}"
name="phone_number_practitioner">
</div>
<label class="j-label">{{trans('personalData.mobileNumber')}}</label>
<div class="j-input">
<input type="tel" value="{{$practitioner->mobile}}"
name="mobile_number_practitioner">
</div>
<label class="j-label">{{trans('personalData.email')}}</label>
<div class="j-input">
<input type="email" value="{{$practitioner->email}}"
name="email_practitioner">
</div>
</div>
</div>
<div class="col-xl-1 j-unit"></div>
<div class="col-sm-12 col-lg-12 col-xl-6">
<div class="j-divider-text j-gap-top-20 j-gap-bottom-45">
<span>{{trans('settings.specialty')}}</span>
</div>
<select name="practitioner_specialty_id_update"
id="practitioner_specialty_id_update"
class="form-control-practitioner required">
#foreach($specialties as $specialty)
<option
value="{{$specialty->specialty_id}}">{{$specialty->name}}</option>
#endforeach
</select>
<label class="j-label">{{trans('personalData.effectiveDate')}}</label>
<div class="j-input">
<input type="date" value="{{$practitioner_specialty->effective_date}}"
name="effective_date_specialty">
</div>
<label class="j-label">{{trans('personalData.expiryDate')}}</label>
<div class="j-input">
<input type="date" value="{{$practitioner_specialty->expiry_date}}"
name="expiry_date_specialty">
</div>
</div>
</div>
</div>
<div class="j-divider j-gap-bottom-45 j-gap-top-10"></div>
<button type="submit"
class="btn btn-editpanel btn-success btn-round">Save changes
</button>
<!-- end /.footer -->
<button id="update-cancel-button-practitioner" type="button"
class="btn btn-editpanel btn-danger btn-round">Cancel
</button>
</div>
</form>
</div>
web.php
Route::post('/practitioner/update/{id}', 'Crud\Settings\PractitionerController#updatePractitioner')->name('updatePractitioner');
Controller:
<?php
namespace App\Http\Controllers\CRUD\Settings;
use App\Models\Practitioner;
use App\Models\PractitionerCompetenceLevel;
use App\Models\PractitionerSpecialty;
use App\Repositories\PractitionerRepository;
use Illuminate\Http\Request;
class PractitionerController extends CrudController
{
protected $repository;
public function __construct(PractitionerRepository $repository)
{
$this->middleware('auth');
$this->repository = $repository;
}
public function updatePractitioner($id, Request $request)
{
$this->validate($request, [
'effective_date_practitioner' => 'required',
'effective_date_specialty' => 'required',
]
);
$input = $request->all();
$input['data'][$this->repository->getIdName()] = $id;
$this->repository->update($input['data']);
return back()->with('successUpdate', 'Practitioner has been updated!');
}
}
My guess is that the data I want to update belongs to two different tables in DB one called practitioner and the other one called practitioner_specialty
As per your code you are trying to do mass assignment to your model
You may do this using the $fillable property on the model
protected $fillable = ['effective_date_practitioner','effective_date_specialty',......];
And you can use attach() method to updated data in related tables

Error when input date on laravel 5.4

I am using Laravel to create a project but I get some issue when creating a form that uses date:
Is there something missing in the table or script?
Here the table
Here the controller
public function index(Request $request){
$data = array();
if($request->isMethod('post') == "post"){
$pendaftar = new PendaftarModel();
$pendaftar->tgl =$request->input(['date']);
$pendaftar->nopol =$request->input('no polisi');
$pendaftar->motor =$request->input('jenis service');
$pendaftar->servis =$request->input('keluhan kendaraan');
$pendaftar->keluhan =$request->input('keluhan kendaraan');
// $pendaftar->keluhan =$request->input('keluhan kendaraan');
if($pendaftar->save()){
$data["status"] = "success";
$data["message"] = "Selamat, booking berhasil. Staff kami akan segera menghubungi anda untuk penjadwalan";
}else {
$data["status"] = "danger";
$data["message"] = "Maaf, Booking Gagal";
}
}
return view("daftar", $data);
The view blade
div class="well well-lg">
<div class="container">
<h2>Booking Online</h2>
<span>Halaman untuk melakukan pendaftaran kendaraan.</span>
</div>
</div>
<div class="container">
<div class="alert alert-info">
<i class="glyphicon glyphicon-info-sign"></i> Silahkan isi data berikut
</div>
<div class="panel panel-primary">
<div class="panel-heading">
Form Data Kendaraan
</div>
<div class="panel-body">
#if(isset($status))
<div class="alert alert-<?php echo $status; ?>">
<?php echo $message; ?>
</div>
#endif
<form method="post">
{{ csrf_field() }}
<div class="form-group">
<label for="tanggal">Pilih Tanggal</label>
<input class="form-control" id="tanggal" required type="date" name="tgl" max="3000-12-31"
min="1000-01-01" placeholder="Pilih Tanggal">
</div>
<div class="form-group">
<label for="nopol">Nomor Polisi:</label>
<input class="form-control" id="nopol" required type="text" name="nopol" placeholder="Masukkan No Polisi">
</div>
<div class="form-group">
<label for="motor">Jenis Motor:</label>
<input class="form-control" id="motor" required type="text" name="motor" placeholder="Matic/Bebek/Sport">
</div>
<div class="form-group">
<label for="servis">Tipe Service:</label>
<input class="form-control" id="servis" required type="text" name="servis" placeholder="Besar/Kecils">
</div>
<div class="form-group">
<label for="keluhan">Keluhan Kendaraan:</label>
<textarea name="keluhan" id="keluhan" required class="form-control" rows="5" placeholder="Tulis Keluhan Motor Anda"></textarea>
</div>
<button type="submit" name="submit" class="btn btn-success btn-lg"><i class="glyphicon glyphicon-send"></i> Submit</button>
<button type="reset" class="btn btn-danger btn-lg">Reset</button>
</form>
</div>
</div>
</div>
The Model
{
//
protected $table = "pendaftar";
public $timestamps = true;
protected $fillable=['tgl','nopol','motor','servis','keluhan'];
}
In the snapshot, Your table is missing updated_at column, create a column with the name "updated_at" in your pendafter table.
Another way you can set the model like this:
{
//
protected $table = "pendaftar";
public $timestamps = false; //it should be false
protected $fillable=['tgl','nopol','motor','servis','keluhan'];
}

Laravel - Edit product with polymorphic relation

I have a system where to user needs to be able to change a product. But the problem is, This product has a polymoprhic relation with theme. This is the build-up
Products
- ID
- productable_id (For instance "1")
- productable_type (Is either "App\Theme"or "App\Plugin")
- name (Just a name)
- description (Just a description)
- etc
Theme
- id (1)
- composer_package
Now I need the user to be able to change a product. Currently, I have it done like this in the controller
public function update(Request $request, $id)
{
$product = Product::find($id);
$product->fill($request->all());
$product->save();
return redirect('/products')->with('flash', $product->name . ' is succesvol bewerkt');
}
But since its a polymorphic relation I don't know how to change for example the "composer_package" that is associated with the selected product. Say, for instance, I want to change the product with the ID of 1. Then I want to also be able to change the composer_package with the id 1 because that one is associated with that selected product. Also, How can I change for instance, the type of product. The selected product is an App\Theme and I want to change that to App\Plugin. How can I achieve the above two things with this polymorphic relation
This is the form that is collecting the data. It's quite large
<div class="modal fade-scale" id="createProduct" tabindex="-1" role="dialog" aria-labelledby="IetsAnders" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="m-0">Product aanmaken</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<form method="POST" action="{{ route('addProduct') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="name">Naam</label>
<input type="text" name="name" class="form-control" placeholder="Naam">
</div>
<div class="form-group">
<label for="description">Omschrijving</label>
<textarea name="description" id="" class="form-control" cols="30" rows="5"></textarea>
</div>
<div class="form-group">
<label for="productable_type">Product type</label>
<select name="type" id="productable_type" class="form-control">
<option selected>Kies een type...</option>
</select>
</div>
<div class="form-group">
<label for="price">Prijs</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="currency" style="background-color: white; border-right: none">€</span>
</div>
<input type="number" step="0.01" name="price" class="form-control" value="" aria-describedby="currency" style="border-left: none" placeholder="00.00">
</div>
</div>
<hr>
<div class="form-group">
<label for="period_id">Betalings periode</label>
<select name="period_id" id="" class="form-control">
<option selected>Kies een periode</option>
#foreach($plans as $plan)
<option>{{ $plan->name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="periodically_price">Prijs per gekozen periode</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="currency" style="background-color: white; border-right: none">€</span>
</div>
<input type="text" name="periodically_price" class="form-control" value="" aria-describedby="currency" style="border-left: none" placeholder="00.00">
</div>
</div>
<div class="form-group mb-3">
<label for="thumbnail">Foto van product</label>
<input type="file" name="thumbnail" class="form-control">
</div>
<div class="form-group mb-3">
<label for="composer_package">Composer package</label>
<input type="text" name="composer_package" class="form-control" placeholder="Composer package">
</div>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Sluiten</button>
<button type="submit" class="btn btn-orange">Bewerken</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
Thanks in advance!
EDIT
Product model
class Product extends Model
{
protected $fillable = [
'productable_type', 'productable_id', 'name', 'description', 'thumbnail', 'price', 'periodically_price', 'period_id'
];
public function productable()
{
return $this->morphTo();
}
public function order_items()
{
return $this->hasMany(Orderitems::class);
}
public function plan() {
return $this->belongsTo(Plan::class, 'period_id');
}
}
Theme Model
class Theme extends Model
{
protected $fillable = [
];
public function webshops()
{
return $this->hasMany(Webshop::class);
}
public function products()
{
return $this->morphMany(Product::class, 'productable');
}
}
Add composer_package to Theme::$fillable.
Adjust the HTML form: name="productable[composer_package]"
Then you can update the theme like this:
$product->productable->update($request->get('productable'))

Angular 5 - Populate form with mysql data

i'm new with angular 5.
I'm trying to populate a form with data from a database.
So far this it hid my form and from the ts side it only shows null.
PHP code:
include ('conexion.php');
$id = $_GET['id'];
$sql = "SELECT * FROM tbl_usuario WHERE id=".$id;
if($con){
if(!$result = mysqli_query($con,$sql)) die();
while($data = mysqli_fetch_assoc($result)){
$arreglo[] = $data;
}
echo json_encode($arreglo);
}else{
die ("error");
}
form.html:(the ngModel i used with or without brackets)
<div class="forms">
<form method="post" *ngFor="let x of datos">
<div class="form-row">
<div class="form-group col-md-4">
<label>Nombre</label>
<input type="text" class="form-control col-10" (ngModel)="x.nombre" name="nombre" value="x.nombre" />
</div>
<div class="form-group col-md-4">
<label>Apellido Paterno</label>
<input type="text" class="form-control col-10" (ngModel)="x.a_paterno" name="a_paterno" value="x.a_paterno" required/>
</div>
<div class="form-group col-md-4">
<label>Apellido Materno</label>
<input type="text" class="form-control col-10" (ngModel)="x.a_materno" name="a_materno" value="x.a_materno" required/>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>Edad</label>
<input type="text" class="form-control col-10" (ngModel)="x.edad" name="edad" value="x.edad" required/>
</div>
<div class="form-group col-md-6">
<label>Carrera</label>
<input type="text" class="form-control col-10" (ngModel)="x.carrera" name="carrera" value="x.carrera" required />
</div>
<div class="col-md-10">
<label>Direccion</label>
<input type="text" class="form-control col-12" (ngModel)="x.direccion" name="direccion" value="x.direccion" required/>
</div>
<div class="col-md-10">
<br>
<label>Telefono</label>
<input type="text" class="form-control col-12" (ngModel)="x.telefono" name="telefono" value="x.telefono" required/>
</div>
</div>
<br>
<button type="submit" class="btn btn-primary">Enviar Datos</button>
<br>
<br>
</form>
</div>
form.ts:
constructor(private http: HttpClient, private router: Router, private route: ActivatedRoute) {
this.mostrarDatos();
}
ngOnInit() {
this.route.params.subscribe(params => {
this.id = params['id']; // (+) converts string 'id' to a number
console.log('Mi id' + this.id);
});
}
mostrarDatos() {
console.log(this.id);
this.http.get('http://localhost/crudu/mostrarID.php?id=' + this.id).subscribe((data) => {
this.datos = data;
console.log(this.datos);
});
}
I've been trying with many solutions but nothing at the end.
Also in my route or url it shows as eUsuario/1
Try to replace (ngModel) with [(ngModel)]. Currently you have a binding from the input into model but not vice versa.
Remove the call of mostrarDatos from the constructor and call it after you get the id.
this.route.params.subscribe(params => {
this.id = params['id']; // (+) converts string 'id' to a number
console.log('Mi id' + this.id);
this.mostrarDatos();
});

Laravel - Get Row ID of selected Item

I'm new to Laravel. I want to check if there is an ID of the selected item and user from my form. Both these fields are in my item_assignments table. Whenever there is no ID found, it will create a new assignment and store it to the item_assignments table. This works but when there is an ID found, it should update the existing one by incrementing the count inputted.
Here is my view.
<form class="form-horizontal" method="post" action="{{url('item/assign')}}" enctype="multipart/form-data">
<input type="hidden" name="_token" value="{{ csrf_token() }}" >
<legend>Assign Item</legend>
<fieldset>
<input id="eid" name="id" type="hidden">
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="name">Item Name:</label>
<div class="col-md-6">
<input id="ename" name="name" type="text" class="form-control input-md" readonly>
</div>
</div>
<!-- Select Basic -->
<div class="form-group{{ $errors->has('user') ? ' has-error' : '' }}">
<label class="col-md-4 control-label" for="user">Assign to:</label>
<div class="col-md-6">
<select id="user" name="user" class="form-control">
<option value="0">Select a User</option>
#foreach($users as $user)
<option value="{{$user->id}}">{{$user->name}}</option>
#endforeach
</select>
#if ($errors->has('user'))
<span class="help-block">
<strong>{{ $errors->first('user') }}</strong>
</span>
#endif
</div>
</div>
<!-- Text input-->
<div class="form-group{{ $errors->has('count') ? ' has-error' : '' }}">
<label class="col-md-4 control-label" for="count">Item Count:</label>
<div class="col-md-6">
<input id="count" name="count" type="text" placeholder="Enter Item Count" class="form-control input-md">
#if ($errors->has('count'))
<span class="help-block">
<strong>{{ $errors->first('count') }}</strong>
</span>
#endif
</div>
</div>
<!-- Button (Double) -->
<div class="form-group">
<label class="col-md-5 control-label" for="submit"></label>
<div class="col-md-7">
<button id="submit" name="submit" class="btn btn-success">Assign</button>
</div>
</div>
</form>
This is my controller
// checks the ID of the selected item
$assign1 = ItemAssign::where("item_id", $req->id)->where('user_id', $req->user)->first();
// this works
if (!($assign1)) {
$assign = new ItemAssign();
$assign->user_id = $req->user;
$assign->item_id = $req->id;
$assign->item_count = $req->count;
$assign->balance = $req->count;
$assign->save();
}
// this is what I want to work
else {
$assign = ItemAssign::find($assign1);
$assign->item_count += $req->count;
$assign->balance += $req->count;
$assign->save();
}
// stores to user table
$user = User::find($req->user);
$user->received += $req->count;
$user->save();
// stores to item table
$item = Item::find($req->id);
$count = $item->item_count;
$item->assigned_count += $req->count;
$item->remaining = $count - $item->assigned_count;
$item->save();
return redirect('assignment');
If you already have an instance of ItemAssign stored in $assign1 you should be able to just update that one instead of using a find.
IE:
else {
$assign1->item_count += $req->count;
$assign1->balance += $req->count;
$assign1->update();
}
else {
$assign = ItemAssign::find($assign1);
$assign->item_count += $req->count;
$assign->balance += $req->count;
$assign->update();
}

Categories