I have a button that when clicked, adds some inputs to a form:
<a #click="addNewText()" class="items-center px-4 py-2 bg-gray-800 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-gray-700 active:bg-gray-900 focus:outline-none focus:border-gray-900 focus:shadow-outline-gray transition ease-in-out duration-150">
<i class="far fa-2x fa-plus-square"></i>
</a>
I am using Laravel 8 and Inertia and want to validate my form. When I try to validate, the form inputs don't show up in $request->input('texts'); if the form is empty. If the form inputs are filled, then they show up?
Here is my controller code:
public function index()
{
$texts = [];
$texts = collect(
[
['skill_level' => null, 'word_count' => null, 'title' => null, 'description' => null, 'category' => null]
]
);
//dd($texts->toJson());
//return the view
return Inertia::render('Client/OrderFormBuilder/GiantIndex', [
"allTexts" => $texts->toJson()
]);
}
public function setOrderDetails(Request $request)
{
$texts = $request->input('texts.*');
$rules = [];
$messages = [];
for ($i = 0; $i < count($texts); $i++)
{
$rules['texts[' . $i . '][skill_level]'] = 'required';
$rules['texts[' . $i . '][word_count]'] = 'required';
$rules['texts[' . $i . '][category]'] = 'required';
//$rules['texts.' . $i . '.title'] = 'required|string|min:5|max:10000';
//$rules['texts.' . $i . '.description'] = 'required|string|min:10|max:10000000';
}
for ($i = 0; $i < count($texts); $i++)
{
$messages['texts[' . $i . '][skill_level].required'] = 'Please Enter Your Desired Skill Level.';
$messages['texts[' . $i . '][word_count].required'] = 'Please Enter Your Desired Word Count.';
$messages['texts[' . $i . '][category].required'] = 'Please Enter Your Desired Category.';
/*
$messages['texts.' . $i . '.title.required'] = 'A Title Is Required For Your Text.';
$messages['texts.' . $i . '.title.string'] = 'Please Enter A Valid Title For Your Text.';
$messages['texts.' . $i . '.title.min'] = 'Please Enter A Minimum Of 5 Characters For Your Title.';
$messages['texts.' . $i . '.title.max'] = 'Please Enter A Maximum Of 10000 Characters For Your Title.';
$messages['texts.' . $i . '.description.required'] = 'A Description Is Required For Your Text.';
$messages['texts.' . $i . '.description.string'] = 'Please Enter A Valid Description For Your Text.';
$messages['texts.' . $i . '.description.min'] = 'Please Enter A Minimum Of 10 Characters For Your Description.';
$messages['texts.' . $i . '.description.max'] = 'Please Enter A Maximum Of 10000000 Characters For Your Description.';
*/
}
//dd($texts, $rules, $messages);
Validator::make($texts, $rules, $messages)->validateWithBag('updateOrderFormBuilder');
}
And here is my Vue form template code:
<div v-for="(singleText, index) in form.texts" v-bind:key="index" class="shadow sm:rounded-md sm:overflow-hidden mt-5">
<div class="bg-white py-6 px-4 space-y-6 sm:p-6">
<div class="col-span-6 sm:col-span-4">
<div>
<label class="block font-medium text-sm text-gray-700" for="skill_level">Skill Level</label>
<input :id="'skill_level_' + index" :name="'texts[' + index + '][skill_level]'" type="text" class="form-input rounded-md shadow-sm mt-1 block w-full" v-model="singleText.skill_level" :autocomplete="'texts[' + index + '][skill_level]'" />
<div v-if="form.error('texts[' + index + '][skill_level]')">
<p class="text-sm text-red-600">
{{ form.error('texts[' + index + '][skill_level]') }}
</p>
</div>
<label class="block font-medium text-sm text-gray-700" for="word_count">Word Count</label>
<input :id="'word_count_' + index" :name="'texts[' + index + '][word_count]'" type="text" class="form-input rounded-md shadow-sm mt-1 block w-full" v-model="singleText.word_count" :autocomplete="'texts[' + index + '][word_count]'" />
<div v-if="form.error('texts[' + index + '][word_count]')">
<p class="text-sm text-red-600">
{{ form.error('texts[' + index + '][word_count]') }}
</p>
</div>
<label class="block font-medium text-sm text-gray-700" for="category">Category</label>
<input :id="'category_' + index" :name="'texts[' + index + '][category]'" type="text" class="form-input rounded-md shadow-sm mt-1 block w-full" v-model="singleText.category" :autocomplete="'texts[' + index + '][category]'" />
<div v-if="form.error('texts[' + index + '][category]')">
<p class="text-sm text-red-600">
{{ form.error('texts[' + index + '][category]') }}
</p>
</div>
</div>
</div>
Finally, here is my Vue code:
props: ['allTexts'],
data: function() {
return {
showingNavigationDropdown: false,
text: {
skill_level: null,
word_count: null,
title: null,
description: null,
category: null,
},
form: this.$inertia.form({
'_method': 'POST',
texts: [],
}, {
bag: 'updateOrderFormBuilder',
resetOnSuccess: false,
}),
}
},
mounted: function () {
this.form.texts = JSON.parse(this.allTexts); //this.allTexts;
console.log(this.form.texts);
},
methods: {
switchToTeam(team) {
this.$inertia.put(route('current-team.update'), {
'team_id': team.id
}, {
preserveState: false
})
},
logout() {
axios.post(route('logout').url()).then(response => {
window.location = '/';
})
},
submit() {
this.$inertia.post(route('create-new-order.set-order-details-by-form', this.form), {
preserveScroll: true
})
},
addNewText() {
if(this.form.texts.length < 20)
{
this.form.texts.push(this.text);
console.log(this.form.texts, this.text);
}
},
removeText: function(index) {
if(this.form.texts.length > 1)
{
this.form.texts.splice(index, 1);
}
}
}
Why, when I click on the submit button does $request->input('texts.*'); not work? It always shows nothing when the form is empty, and only shows the inputs when they have been filled in the form?
I think you need to use and send your form.text data. Notice that your inertia.post() are using different parameter
Related
I have here a datatable with a form inside that has 3 submit buttons. I did a switch statement which it checks what submit button was clicked, then performs the operation of that submit button on my store() function. Currently, I'm trying to submit the form using ajax. If I remove the switch statement, and just return one operation/function.e.g. saveCredit(), then it saves data in the database. However, with switch statement, in place, it doesn't save any data.
Also, another instance is if I remove the e.preventDefault(), it saves data in the database but it redirects to make-a-sale/save-purchase route which should not be. It must redirect to the same page. How can I make the submit buttons save the data in the database even with switch statement and e.preventDefault() in place? How can make it redirect to the current page? What am I doing wrong here?
Please see my controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\{
Customer\BillingInfo,
Customer,
Product,
Purchases,
SetupBusiness
};
use App\Traits\PrintReceiptTrait;
use Carbon\Carbon;
use Picqer;
use Auth;
class PurchasesController extends Controller
{
use PrintReceiptTrait;
public function index()
{
return view('make-a-sale.index', ['has_id' => false]);
}
public function indexWithId($product_id)
{
return view('make-a-sale.index', ['product_id' => $product_id, 'has_id' => true]);
}
public function create()
{
return view('make-a-sale.index');
}
public function computeAndConvertData(Request $request)
{
$qty_per_item = array_map('intval', $request->qty);
$zero = floatval('0.00');
$payment = floatval($request->payment);
$total = floatval($request->total);
$balance = $total - $payment;
$new_data = array(
'qty_per_item' => $qty_per_item,
'zero' => $zero,
'payment' => $payment,
'total' => $total,
'balance' => $balance
);
return $new_data;
}
public function saveCredit(Request $request)
{
$product_ids = array_map('intval', $request->product_id);
$cod = $this->computeAndConvertData($request);
$data = $this->createData($request, $product_ids, $cod['qty_per_item'], $cod['balance']);
$this->createPurchaseData($data, $product_ids, $cod['qty_per_item'], $cod['zero'], $cod['total']);
$this->updateProductQtyOnHand($product_ids, $cod['qty_per_item']);
return redirect()->route('make-a-sale.index');
}
public function savePurchaseAndPrint(Request $request)
{
$product_ids = array_map('intval', $request->product_id);
$cod = $this->computeAndConvertData($request);
$payment = $cod['payment'] == $cod['zero'] ? $cod['zero'] : $request->payment;
$balance = $cod['balance'] != $cod['zero'] ? $request->total : $cod['balance'];
$data = $this->createData($request, $product_ids, $cod['qty_per_item'], $balance);
$purchase = $this->createPurchaseData($data, $product_ids, $cod['qty_per_item'], $payment, $balance);
$this->updateProductQtyOnHand($product_ids, $cod['qty_per_item']);
return $this->printReceipt($purchase->code, $purchase->barcode, $purchase->product_id, $purchase->qty_per_item, $purchase->balance);
}
public function savePurchase(Request $request)
{
$product_ids = array_map('intval', $request->product_id);
$cod = $this->computeAndConvertData($request);
$data = $this->createData($request, $product_ids, $cod['qty_per_item'], $cod['balance']);
$this->createPurchaseData($data, $product_ids, $cod['qty_per_item'], $request->payment, $cod['balance']);
$this->updateProductQtyOnHand($product_ids, $cod['qty_per_item']);
return redirect()->route('make-a-sale.index');
}
public function store(Request $request)
{
switch($request->get('action_create')) {
case 'credit':
$this->saveCredit($request);
break;
case 'save_and_print':
$this->savePurchaseAndPrint($request);
break;
case 'save':
$this->savePurchase($request);
break;
default:
return redirect()->route('make-a-sale.index');
}
}
private function generateRandomNumbers($length = 12)
{
$num = '0123456789';
$num_length = strlen((string)$num);
$random_number = '';
for ($i = 0; $i < $length; $i++) {
$random_number .= $num[rand(0, $num_length - 1)];
}
return $random_number;
}
private function generateBarcode($code_to_convert)
{
$generator = new Picqer\Barcode\BarcodeGeneratorHTML();
$barcode = $generator->getBarcode($code_to_convert, $generator::TYPE_CODE_128, 2, 35);
return $barcode;
}
public function createData(Request $request, $product_ids, $qty_per_item, $balance)
{
$code = $this->generateRandomNumbers();
$validation = $request->validate([
'code' => 'unique:purchases',
'product_id' => 'required',
'customer_id' => 'required'
]);
$data = array_merge($validation, [
'code' => $code,
'barcode' => $this->generateBarcode($code),
'status' => 'Regular',
'type' => $balance == floatval('0.00') ? 'Sale' : 'Accounts Receivables',
'cashier_id' => Auth::user()->id,
'customer_id' => $request->customer_id,
'product_id' => $product_ids,
'no_of_items' => $request->no_of_items,
'qty_per_item' => $qty_per_item,
'payment_type' => $balance <= 0 ? 'cash' : 'credit',
'total' => $request->total,
'created_at' => Carbon::now()->timestamp
]);
return $data;
}
public function createPurchaseData($data, $product_id, $qty_sold, $payment, $balance)
{
$purchases = Purchases::create(array_merge($data, [
'payment' => $payment,
'balance' => $balance,
'product_details' => $this->createProductsDetails($product_id, $qty_sold)
]));
return $purchases;
}
public function updateProductQtyOnHand($product_ids, $qty_per_item)
{
$products = array_combine($product_ids, $qty_per_item);
foreach ($products as $product_id => $receive_item_qty) {
$qty_on_hand = Product::where('id', '=', $product_id)->value('qty_on_hand');
$difference = $qty_on_hand - $receive_item_qty;
Product::select('qty_on_hand')->where('id', '=', $product_id)->update(['qty_on_hand' => $difference]);
}
}
}
Here's my route:
Route::post('make-a-sale/save-purchase', [PurchasesController::class, 'store'])->name('make-a-sale.store');
Here's some of my Ajax:
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$(document).ready(function() {
$.noConflict();
var tableId = '#tbl-make-a-sale';
// Footer button group actions
saveCredit(tableId);
savePurchase(tableId);
});
function saveCredit(tableId) {
$('#btn-credit').on('click', function(e) {
e.preventDefault();
if (!$("input[name='product_id[]']").val()) {
toastr.error('The table is empty. Please add some products first.');
} else {
let productIds = $("input[name='product_id[]']").map(function(){ return $(this).val(); }).get();
let qtyPerItem = $("input[name='qty[]']").map(function(){ return $(this).val(); }).get();
let params = {
product_id: productIds,
qty: qtyPerItem,
no_of_items: $("input[name='no_of_items']").val(),
customer_id: $("input[name='customer_id']").val(),
payment: parseFloat($('input[name="payment"]').val()),
total: parseFloat($('input[name="total"]').val()),
_token: $('meta[name="csrf-token"]').attr('content')
}
$.ajax({
url: 'make-a-sale/save-purchase',
type: 'POST',
data: params,
success: function(data) {
toastr.success("A new ledger has been created!");
$(tableId).DataTable().clear().draw(false);
$('#search-customers').val('0').trigger('change.select2').prop('disabled', true);
$('#cash-container, #txt-amount-due').hide();
},
error: function(xhr, status, error) {
let errors = xhr.responseJSON.errors;
for (var key in errors) {
if (errors.hasOwnProperty(key)) {
toastr.error(errors[key]);
}
}
}
});
}
});
}
function savePurchase(tableId) {
$('#btn-save').on('click', function(e) {
e.preventDefault();
if (!$("input[name='product_id[]']").val()) {
toastr.error('The table is empty. Please add some products first.');
} else {
let productIds = $("input[name='product_id[]']").map(function(){ return $(this).val(); }).get();
let qtyPerItem = $("input[name='qty[]']").map(function(){ return $(this).val(); }).get();
let params = {
product_id: productIds,
qty: qtyPerItem,
no_of_items: $("input[name='no_of_items']").val(),
customer_id: $("input[name='customer_id']").val(),
payment: parseFloat($('input[name="payment"]').val()),
total: parseFloat($('input[name="total"]').val()),
_token: $('meta[name="csrf-token"]').attr('content')
}
$.ajax({
url: 'make-a-sale/save-purchase',
type: 'POST',
data: params,
success: function(data) {
toastr.success("Products have been sold successfully!");
$(tableId).DataTable().clear().draw(false);
$('#search-customers').val('0').trigger('change.select2').prop('disabled', true);
$('#cash-container, #txt-amount-due').hide();
},
error: function(xhr, status, error) {
let errors = xhr.responseJSON.errors;
for (var key in errors) {
if (errors.hasOwnProperty(key)) {
toastr.error(errors[key]);
}
}
}
});
}
});
}
Here's my HTML:
<form id="form-make-a-sale" action="{{ route('make-a-sale.store') }}" method="post" enctype="multipart/form-data">
#csrf
<table id="tbl-make-a-sale" class="w-full tbl-responsive overflow-x-auto rounded-lg border-none tbl-default">
<thead class="w-min">
<tr>
<th
class="px-6 py-0 bg-persian-blue h-16 text-left text-xs text-white uppercase tracking-wider border-none">Actions</th>
<th
class="px-6 py-0 bg-persian-blue h-16 text-left text-xs text-white uppercase tracking-wider border-none">
Barcode
</th>
<th
class="px-6 py-0 bg-persian-blue h-16 text-left text-xs text-white uppercase tracking-wider border-none">
Name
</th>
<th
class="px-6 py-0 bg-persian-blue h-16 text-left text-xs text-white uppercase tracking-wider border-none">
Description
</th>
<th
class="px-6 py-0 bg-persian-blue h-16 text-left text-xs text-white uppercase tracking-wider border-none">
Qty. On Hand
</th>
<th
class="px-6 py-0 bg-persian-blue h-16 text-left text-xs text-white uppercase tracking-wider border-none">
Qty. To Sell
</th>
<th
class="px-6 py-0 bg-persian-blue h-16 text-left text-xs text-white uppercase tracking-wider border-none hidden">
SRP
</th>
<th
class="px-6 py-0 bg-persian-blue h-16 text-left text-xs text-white uppercase tracking-wider border-none">
Ext. Price
</th>
</tr>
</thead>
<tbody class="bg-white"></tbody>
</table>
<div class="w-full pb-6 md:pb-0 border-t border-gray-200 md:border-none">
<div class="flex bg-white justify-between items-center">
<div class="pt-6 pb-0 px-6 whitespace-no-wrap">
<p class="text-2xl text-gray-700 font-bold">Total</p>
</div>
<div class="pt-6 pb-0 px-6 whitespace-no-wrap">
<p class="text-4xl text-gray-700 font-extrabold font-mono text-right">
<span id="total">₱ 0.00</span>
<input type="hidden" name="total" readonly/>
</p>
</div>
</div>
<div id="cash-container" style="display: none;">
<div class="flex justify-between items-center">
<div class="px-6 whitespace-no-wrap">
<p class="text-lg text-gray-700 font-bold">Cash</p>
</div>
<div class="px-6 whitespace-no-wrap">
<p class="text-lg text-gray-700 font-extrabold font-mono text-right">
<span id="cash">0.00</span>
</p>
</div>
</div>
</div>
</div>
<div class="mt-4 w-full md:border-t md:border-b md:border-gray-200">
<div id="amount-due-container" class="flex bg-persian-blue md:bg-white justify-between items-center">
<div class="p-6 whitespace-no-wrap">
<p id="lbl-amount-due" class="text-2xl text-gray-50 md:text-gray-700 font-bold">Amount Due</p>
</div>
<div class="p-6 whitespace-no-wrap">
<p id="txt-amount-due" class="text-3xl text-gray-50 md:text-gray-700 font-extrabold font-mono text-right">
<span id="amount_due"></span>
</p>
</div>
</div>
</div>
<div id="btn-footer-group-mas" class="m-6 justify-between">
<button type="button" class="px-8 py-4 text-md font-medium text-gray-50 transition-colors duration-300 transform bg-red-400 hover:bg-red-500 rounded hover:text-white focus:outline-none focus:ring cstm-size-m-mas cstm-size-w-full-mas btn-clear" name="clear" value="clear" tabindex="2">Clear
</button>
<div id="btn-footer-right-group-mas">
<button type="button" id="btn-cash" class="px-8 py-4 text-md font-medium text-white transition-colors duration-300 transform rounded bg-green-400 hover:bg-green-300 focus:outline-none focus:ring cstm-size-m-mas cstm-size-w-full-mas" data-hystmodal="#pay-in-cash-modal" tabindex="3">Cash
</button>
<button type="submit" id="btn-credit" class="px-8 py-4 text-md font-medium text-white transition-colors duration-300 transform rounded bg-yellow-400 hover:bg-yellow-300 focus:outline-none focus:ring cstm-size-m-mas cstm-size-w-full-mas credited" name="action_create" value="credit" tabindex="4">Credit
</button>
<button type="submit" id="btn-save-and-print" class="px-8 py-4 text-md font-medium text-indigo-400 transition-colors duration-300 transform border-2 border-indigo-400 rounded bg-indigo-100 hover:bg-indigo-200 focus:outline-none focus:ring disabled:opacity-40 cursor-not-allowed cstm-size-m-mas cstm-size-w-full-mas" name="action_create" value="save_and_print_receipt" tabindex="5">Save and Print Receipt
</button>
<button type="submit" id="btn-save" class="px-8 py-4 text-md font-medium text-white transition-colors duration-300 transform rounded bg-indigo-600 rounded hover:bg-indigo-500 focus:outline-none focus:ring cstm-last-el-size-m-mas cstm-size-w-full-mas" name="action_create" value="save" tabindex="6">Save
</button>
</div>
</div>
</form>
Any help is much appreciated.
On the controller side instead of redirecting to the route, you can redirect JSON to the Ajax at frontend.
For Example:
Instead of:
return redirect()->route('make-a-sale.index');
You can:
return response()->json(["status"->true]);
your question I doesn't understand but first check on submit Your Ajax send request to your controller function of not...
2nd thing, you don't need to write hardcoded url in ajax request...
$.ajax({
type: "GET",
url: "{{ route('home') }}?page="+ page,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
// data: { id: deal_id, }
}).done(function( data ) {
//on success do your operation
})
.fail(function(jqXHR, ajaxOptions, thrownError)
alert('No response from server');
});
If you want to pass Param in URL like domainname.com/user/edit/{id}
then you can pass to ajax as above same URL using route you...
simply do as like below
user_id = 3; //on click get user_id
url = "{{ route('admin.users.edit',':id') }}";
url = url.replace(':id', user_id);
then that url variable pass to ajax
$.ajax({
type: "POST",
url: url,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
// data: { id: deal_id, }
}).done(function( data ) {
//on success do your operation
})
.fail(function(jqXHR, ajaxOptions, thrownError)
alert('No response from server');
});
Sorry #Harsh Patel if I cannot explain my question well.
I managed to solved it by:
return response()->json([$data]);
And adding redirect per case in my switch statement:
return redirect()->route('make-a-sale.index');
Switch statement:
public function store(Request $request)
{
switch($request->get('action_create')) {
case 'credit':
$this->saveCredit($request);
return redirect()->route('make-a-sale.index');
break;
case 'save_and_print':
$this->savePurchaseAndPrint($request);
break;
case 'save':
$this->savePurchase($request);
return redirect()->route('make-a-sale.index');
break;
default:
return redirect()->route('make-a-sale.index');
}
}
Thank you #Shree Sthapit
[1]so i have a laravel project going on, and i want to increment the value of the variable deliver_later_num, depending on the "deliver_today" present in the same component in the items[] array, which i am outputting in the template file, i cannot figure how to do it, i do not know if i can increment the value on the template side or on the component side. here is the component code:
cartContent = new Vue({
el: '#cartList',
data: {
items: [], //array containing all the items
deliver_later_num: 0, //value to increment
},
methods: {
remove: function (product_id) {
removeProductIfFromCart(product_id);
},
incQuantity: function (product_id){
incCart(product_id)
},
decQuantity: function (product_id){
decCart(product_id)
},
}
})
here is the template file :
<div id="cartList">
<div v-for="item in items" class="items col-xs-12 col-sm-12 col-md-12 col-lg-12 clearfix">
<div class="info-block block-info clearfix" v-cloak>
<div class="square-box pull-left">
<img :src="item.attributes.image" class="productImage" width="100" height="105" alt="">
</div>
<h6 class="product-item_title">#{{ item.name }}</h6>
<p class="product-item_quantity">#{{ item.quantity }} x #{{ item.attributes.friendly_price }}</p>
<ul class="pagination">
<li class="page-item">
<button v-on:click="decQuantity(item.id)" :value="item.id" class="page-link" tabindex="-1">
<i class="fa fa-minus"></i>
</button>
</li>
<li class="page-item">
<button v-on:click="incQuantity(item.id)" :value="item.id" class="page-link" >
<i class="fa fa-plus"></i>
</button>
</li>
<li class="page-item">
<button v-on:click="remove(item.id)" :value="item.id" class="page-link" >
<i class="fa fa-trash"></i>
</button>
</li>
<input hidden class="delivers_today_state" type="text" :value=" item.attributes.delivers_today "> // if this equals 0 i want to increment the deliver_later_num value
</ul>
</div>
</div>
</div>
laravel controller code :
public function add(Request $request){
$item = Items::find($request->id);
$restID=$item->category->restorant->id;
//Check if added item is from the same restorant as previus items in cart
$canAdd = false;
if(Cart::getContent()->isEmpty()){
$canAdd = true;
}else{
$canAdd = true;
foreach (Cart::getContent() as $key => $cartItem) {
if($cartItem->attributes->restorant_id."" != $restID.""){
$canAdd = false;
break;
}
}
}
//TODO - check if cart contains, if so, check if restorant is same as pervious one
// Cart::clear();
if($item && $canAdd){
//are there any extras
$cartItemPrice=$item->price;
$cartItemName=$item->name;
$theElement="";
//Is there a varaint
//variantID
if($request->variantID){
//Get the variant
$variant=Variants::findOrFail($request->variantID);
$cartItemPrice=$variant->price;
$cartItemName=$item->name." ".$variant->optionsList;
//$theElement.=$value." -- ".$item->extras()->findOrFail($value)->name." --> ". $cartItemPrice." ->- ";
}
foreach ($request->extras as $key => $value) {
$cartItemName.="\n+ ".$item->extras()->findOrFail($value)->name;
$cartItemPrice+=$item->extras()->findOrFail($value)->price;
$theElement.=$value." -- ".$item->extras()->findOrFail($value)->name." --> ". $cartItemPrice." ->- ";
}
Cart::add((new \DateTime())->getTimestamp(), $cartItemName, $cartItemPrice, $request->quantity, array('id'=>$item->id,'variant'=>$request->variantID, 'extras'=>$request->extras,'restorant_id'=>$restID,'image'=>$item->icon,'friendly_price'=> Money($cartItemPrice, env('CASHIER_CURRENCY','usd'),true)->format(),'delivers_today' => $item->deliverstoday ));
return response()->json([
'status' => true,
'errMsg' => $theElement
]);
}else{
return response()->json([
'status' => false,
'errMsg' => __("You can't add items from other restaurant!")
]);
//], 401);
}
}
public function getContent(){
//Cart::clear();
return response()->json([
'data' => Cart::getContent(),
'total' => Cart::getSubTotal(),
'status' => true,
'errMsg' => ''
]);
}
link to the items array vue dev tools screenshot
[1]: https://i.stack.imgur.com/smLRV.png
thanks for your precious help and time.
A computed property can be used if the deliver_later_num is only dependent on the presence/absence of deliver_today on elements of items array
cartContent = new Vue({
el: '#cartList',
data: {
items: {}
},
computed: {
deliver_later_num() {
let num = 0;
Object.keys(this.items).forEach(key => {
let item = this.items[key];
Object.keys(item).forEach(k => {
if(k === 'deliver_today' && item[k]) {
num++;
}
});
});
return num;
},
}
Hello can someone please help me because I wanted to use ajax in my laravel form, when everytime I hit 'CREATE POST' button, the table contains all my posts will hide and then the form will show, and when clicking the submit button in the form the table will then show with its new data inserted below the table and the form will hide. I have a code but it is not working.
Controller Code:
public function store(Request $request)
{
//validate the data
$this->validate($request, array(
'title' => 'required|max:255',
'slug' => 'required|alpha_dash|min:5|max:255|unique:posts,slug',
'category_id' => 'required|integer',
'body' => 'required',
'featured_image' => 'image|nullable|max:1999'
));
//store in the database
$post = new Post;
$post->title = $request->title;
$post->slug = $request->slug;
$post->category_id = $request->category_id;
$post->body = Purifier::clean($request->body);
//Save Our Image
if ($request->hasFile('featured_image')) {
$image = $request->file('featured_image');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('images/'. $filename);
Image::make($image)->resize(800, 400)->save($location);
$post->image = $filename;
}
$post->save();
return response()->json($post);
// Session::flash('success', 'The blog post was succesfully saved!');
// //redirect to another page
// return redirect()->route('posts.show', $post->id);
}
Route:
Route::resource('/posts', 'PostController');
Route::post('/addpost', 'PostController#store');
Form Code:
{!! Form::open(['id' => 'form-post', 'method' => 'POST', 'route' => 'posts.store', 'data-parsley-validate' => '', 'files' => true]) !!}
{{ csrf_field() }}
<div class="form-group">
<label class="control-label" for="title">Title:</label>
<input type="text" name="title" class="form-control" data-error="Please enter title." required />
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label class="control-label" for="title">Slug:</label>
<input type="text" name="slug" class="form-control" data-error="Please enter title." required />
<div class="help-block with-errors"></div>
</div>
{{ Form::label('category_id', 'Category') }}
<select id="add-category" class="form-control" name="category_id">
#foreach($categories as $category)
<option value='{{ $category->id }}'>{{ $category->name }}</option>
#endforeach
</select>
{{ Form::label('featured_image', 'Upload Featured Image:', ['class' => 'form-spacing-top']) }}
{{ Form::file('featured_image',["id" => 'add-image', "class" => 'form-control-file']) }}
{{ Form::label('body', 'Post Body:') }}
{{ Form::textarea('body', null, array('id' => 'add-body', 'class' => 'form-control')) }}
{{ Form::button('Create Post', array('id' => 'submit-post', 'class' => 'btn btn-success btn-lg btn-block', 'style' => 'margin-top: 20px;'))}}
{!! Form::close() !!}
</div>
</div>
Ajax Code:
$(document).on('click', '.create-post', function() {
$('.create-form').css('display','block');
$('.posts-table').css('display','none');
});
$('#submit-post').click(function(e) {
e.preventDefault();
var action = $('#form-post').attr('route');
var title = $("#form-post").find("input[name='title']").val();
var slug = $("#form-post").find("input[name='slug']").val();
var category_id = $("#add-category").val();
var featured_image = $("#add-image").val();
var body = $("#add-body").val();
$.ajax({
type : 'POST',
url : "/addpost",
headers: {
'X-CSRF-TOKEN' : $('input[name="_token"]').val()
},
data : {
title: title,
slug: slug,
category_id: category_id,
featured_image: featured_image,
body: body
},
success: function(data){
$('.create-form').css('display','none');
$('.posts-table').css('display','block');
$('.table tbody').append("<tr id='" + data.id + "' class='item'><th>" + data.id + "</th><td>" + data.title + "</td><td>" + data.body + "</td><td>date</td><td><button class='show-modal btn btn-success' data-id='" + data.id + "' data-title='" + data.title + "' data-slug='" + data.slug + "' data-category='" + data.category_id + "' data-image='" + data.featured_image + "' data-body='" + data.body + "'><span class='glyphicon glyphicon-eye-open'></span> Show</button><button class='edit-modal btn btn-info' data-id='" + data.id + "' data-title='" + data.title + "' data-slug='" + data.slug + "' data-category='" + data.category_id + "' data-image='" + data.featured_image + "' data-body='" + data.body + "'><span class='glyphicon glyphicon-edit'></span> Edit</button><button class='delete-modal btn btn-danger' data-id='" + data.id + "' data-title='" + data.title + "' data-slug='" + data.slug + "' data-category='" + data.category_id + "' data-image='" + data.featured_image + "' data-body='" + data.body + "'><span class='glyphicon glyphicon-trash'></span> Delete</button></td></tr>");
console.log(data);
}
});
});
It's not enough information about the error.
Try dd() in your controller & check it in [F12 -> Network].
And since you're using ajax to sending request, there no need to define options (action, route) in Form. remove it.
I've been trying to make an attendance management system in Laravel.
In the attendance view,when a checkbox is checked ,the controller function is supposed to increment the appropriate database column.
I've been having some issues.Here's my code:
views:
<div class="container">
<!--<div class="row">-->
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Take Attendance</div>
<h4><center>Teacher: {{ auth()->user()->name}}</center></h4>
<div class="form-inline">
#foreach ($second as $sec)
<br>
<div class = "form-group">
{{$sec->Roll }}
    
{{ $sec->Name}}
</div>
<div class = "form-group">
<!--{{Form::checkbox('agree') }}-->
<input tabindex="1" type="checkbox" value="{{$sec->Roll}}" name="" />
</div>
#endforeach
</div>
<br>
<form action ="report_generate&<?php echo $name ?>" method = "post" enctype = "multipart/form-data" >
<!--<input type = "hidden" name = "_token" value = "{{{ csrf_token() }}}"/>-->
<div class = "form-group">
<input type="submit" value= "Submit">
<center>Report</center>
</div>
</form>
</div>
</div>
</div>
Controller(for submit button):
public function report_generate($tabu)
{
$year = DB::table('sub')->select('Year')-
>where('sub.Subject_Name','=',$tabu)->get();
$sub_id = DB::table('sub')->select('Subject_Id')-
>where('sub.Subject_Name','=',$tabu)->get();
ob_start();
echo $year;
$output=ob_get_contents();
ob_end_clean();
if ( $output=='[{"Year":1}]')
{
$req = "first";
}
elseif ( $output=='[{"Year":2}]')
{
$req = "second";
}
elseif ( $output=='[{"Year":3}]')
{
$req = "third";
}
elseif ( $output=='[{"Year":4}]')
{
$req = "fourth";
}
$final = DB::table($req)->get();
//dd($final);
//$columns = Schema::getColumnListing($req);
//dd($sub_id);
ob_start();
echo $sub_id;
//dd($sub_id);
$va=ob_get_clean();
$va = stripslashes($va);
$txt = rtrim($va,"}]");
$txt = ltrim($txt,"[{Subject_Id:");
$txt = ltrim($txt,"Subject_Id:");
$txt = explode(":",$txt);
$txt = str_replace('"','', $txt);
//dd($txt[1]);
$columns = Schema::getColumnListing($req);
//dd($columns);
//dd($txt);
foreach ($columns as $col)
{
//dd("Y");
if($col == $txt[1])
{
$got=DB::table($req)->select($col)->get();
//dd($got);
foreach($got as $g)
{
//want to increment that cell value
}
}
}
}
Looks like your checkboxs are outside of the form divs which is an issue. You also seem to be skipping over the Laravel features, for example having a Sub Model you can call on, or using the Request facade. Also not sure why you're using ob for those string comparisons (might actually want to look at Switch for that long elseif block) Lastly, you might want to to use a raw DB statement to do the increments within a SQL query
DB::statement("UPDATE " . $table . " set " . $column . " to " . $column . " + 1 WHERE id IN (" implode(', ', $ids) . ')")
I am using for the most part the default code from the dynatable website for a stylized list.
I really like it as i get search on all my fields. here is the html code and the javascript code:
<ul id="ul-example" class="row-fluid no-bullets">
<?php foreach ($dms as $k => $v): ?>
<li class="span12" data-color="gray" id="manage_vehicle_id_<?= $v['id'];?>">
<div class="thumbnail">
<div class="thumbnail-image">
<center>
<img src="<?= $v['image']; ?>" width="220" height="180" />
</center>
</div>
<div class="caption">
<center>
<h5><?= $v['year'] . ' ' . $v['make'] . ' ' . $v['model'] . ' ' . $v['trim'];?></h5>
</center>
<hr>
<center>
<p><b>Vin:</b> <?= $v['vin']; ?></p>
<p><b>Stock #:</b> <?= $v['stock'];?></p>
</center>
<hr>
<p>
<center>
<button class="btn btn-primary" onclick="getVehicleDetailsByid('<?= $v['id']; ?>');"><i class="fa fa-edit"></i> Edit</button>
<button class="btn btn-danger" onclick="openDeleteVehicleByIdModal('<?= $v['id']; ?>', '<?= $v['vin']; ?>', '<?= $v['stock'];?>');"><i class="fa fa-minus"></i> Delete</button>
</center>
</p>
</div>
</div>
</li>
<?php endforeach; ?>
</ul>
function ulWriter(rowIndex, record, columns, cellWriter) {
var cssClass = "span12", li;
if (rowIndex % 3 === 0) { cssClass += ' first'; }
li = '<li class="' + cssClass + '" id="'+record.id+'" data-row-index="'+rowIndex+'"><div class="thumbnail"><div class="thumbnail-image">' + record.thumbnail + '</div><div class="caption">' + record.caption + '</div></div></li>';
return li;
}
// Function that creates our records from the DOM when the page is loaded
function ulReader(index, li, record) {
var $li = $(li),
$caption = $li.find('.caption');
record.thumbnail = $li.find('.thumbnail-image').html();
record.caption = $caption.html();
record.label = $caption.find('h5').text();
record.description = $caption.find('p').text();
record.color = $li.data('color');
record.id = $li.attr('id');
record.index = $li.attr('data-row-index');
}
$( '#ul-example' ).dynatable({
table: {
bodyRowSelector: 'li'
},
writers: {
_rowWriter: ulWriter
},
readers: {
_rowReader: ulReader
},
features: {
paginate: false,
sort: true,
search: true,
recordCount: true,
perPageSelect: false
},
inputs: {
searchTarget: '#manage_vehicle_search',
recordCountTarget: '#manage_vehicle_recordCount'
}
});
as you can see in the html i have a delete button that removes the record. I can remove it manually. However it is not actually removed. When a search query happens the item is still in the list.
I remove it with:
$( '#manage_vehicle_id_'+id ).remove();
var dynatable = $('#ul-example').data('dynatable');
dynatable.domColumns.removeFromArray(index);
dynatable.dom.update();
I am getting an error here something like column.length is null. I can see the this.remove method in dynatable is throwing an error.
How can i remove this item from the list and update dynatable dom and the get the right count?
Thanks
I solved this issue by using dynatable.process() instead of remove/update. Not sure if it's the proper solution, but it worked for me.
$( '#manage_vehicle_id_'+id ).remove();
var dynatable = $('#ul-example').data('dynatable');
dynatable.process();