laravel store combined data as object in a single field - laravel

I am trying to store repeater data in database Using laravel. But for that I need to combine some data with different values.
my form looks like this--
<div v-for="(tab, tabIndex) in tabs" :key="tab.id">
<div class="col-md-4 offset-md-4 d-flex">
<label>HouseAreaTypes</label>
</div>
<div class="col-md-4 offset-md-4 d-flex">
<select
v-model="tab.selectedHouseType"
#change="getDecor(tabIndex)"
name="houseAreaTypeId">
<option v-for="houseType in houseTypes" :key="houseType.id" :value="houseType.id">{{ houseType.name }}</option>
</select>
<div class="col-md-4">
<button #click="addTab">
<i class="fa fa-plus"></i>
</button>
<button v-if="tabIndex > 0" class="btn btn-danger btn-sm mt-2 ml-2" #click="removeTab(tabIndex, tab)">
<i class="fa fa-minus"></i>
</button>
</div>
</div>
<div v-for="(row, rowIndex) in tab.rows" :key="row.id">
<table class="table table-borderless col-md-12">
<thead>
<th>DecorationType</th>
<th>Description</th>
<th class="col-md-2">Rate</th>
<th>Quantity</th>
<th class="col-md-2">TotalAmount</th>
<th class="col-md-2"></th>
</thead>
<tbody>
<td>
<select
v-model="row.selectedDecor"
#change="getDescription(tabIndex,rowIndex) "name="decId">
<option v-for="decorType in tab.decorTypes" :key="decorType.id" :value="decorType.id">
{{ decorType.name }}
</option>
</select>
</td>
<td class="col-md-3">
<input type="text" name="des" v-model="row.selectedDes"/>
</td>
<td class="col-md-2">
<input type="number" name="rate" v-model="row.selectedRate" #change="calculateLineTotal(tabIndex,rowIndex)"
/>
</td>
<td class="col-md-1">
<input type="number" min="0" name="qty" v-model="row.selectedQty" #change="calculateLineTotal(tabIndex,rowIndex)"
/>
</td>
<td class="col-md-3">
<input
type="number" name="totalAmount" v-model="row.line_total"/>
</td>
<td>
<button v-if="rowIndex == Object.keys(tab.rows).length -1" type="button" class="btn btn-success btn-sm mt-2 ml-2" #click="addRow(tabIndex)">
<i class="fa fa-plus"></i>
</button>
<button type="button"
#click="removeRow(rowIndex, row,tabIndex)">
<i class="fa fa-minus"></i>
</button>
</td>
</tbody>
</table>
<hr />
</div>
</div>
my migration looks like this--
Schema::create('house_area_carts', function (Blueprint $table) {
$table->id();
$table->integer('houseAreaTypeId')->nullable();
$table->text('houseAreaCartInfo')->nullable()->comment('Object (decorationTypeId, descriptionOfDecoration, qty, rate, totalAmount)');
$table->timestamps();
});
I already have done the frontend part using vue. Here I need to store multiple houseAreaTypeId but in the houseAreaCartInfo I need to commbine decorationTypeId, descriptionOfDecoration, qty, rate, totalAmount these datas. I am attaching an image so you understand well
Iamge to understand the topic
updates
in my controller --
public function createCart(Request $request, $id)
{
$cart = HouseAreaCart::create([
'houseAreaTypeId' => $request->houseAreaTypeId,
'houseAreaCartInfo' => $request->get('houseAreaCartInfo'),
'houseAreaCartInfo' =>[
'rate' => $request->rate,
'qty' => $request->qty,
'decId' => $request->decId,
'des' => $request->des,
'totalAmount' => $request->totalAmount
]
]);
dd($cart);
return response()->json($cart);
}
I am getting this after dd.
"houseAreaTypeId" => "2"
"houseAreaCartInfo" => "{"rate":["11","2"],"qty":["8","1"],"decId":["2","3"],"des":["Nostrum dolorem qui","Veniam architecto l"],"totalAmount":["88.00","2.00"]}"
But when I add another houseAreaTypeId it's showing only the last houseAreaTypeId I added.
Now how do I process multiple houseAreaTypeId in my controller and save it in the database?

The easieast way will be attribute casting to json or array:
// add to the model:
protected $casts = [
'houseAreaCartInfo' => 'array',
];
https://laravel.com/docs/9.x/eloquent-mutators#array-and-json-casting
In the controller you would simply assign to the model an array from your request (or use update method on the model - will work the same):
$cartModel->houseAreaCartInfo = $request->get('houseAreaCartInfo');
then whenever you get that value it will come as an array (same as in the request):
$cartModel->houseAreaCartInfo
[
'des' => ...,
'qty' => ...,
...
]
In your request I suggest validation to make sure this value comes as an array and is stored properly
https://laravel.com/docs/9.x/validation#validating-arrays

Your migration should like,
$table->text('houseAreaCartInfo')->nullable()
anf then, Make sure your request is something like the following,
$request = [
'houseAreaTypeId' => 'required|int', //or array as your choice
'houseAreaCartInfo' => 'required|array',
'houseAreaCartInfo.*.decerationType' => 'required|array', //or int as your choice
'houseAreaCartInfo.*.description' => 'required|string',
'houseAreaCartInfo.*.rate' => 'required|int',
'houseAreaCartInfo.*.quantity' => 'required|int',
];
Then in your model, cast the column as array,
protected $cast = [
'houseAreaCartInfo' => 'array'
];
Finally, you can create model by using eloquent, There should be no error.

Related

Problem with Laravel CRUD (Edit Function)

Good day everyone. I'm quite new to new to Laravel and was doing some basic CRUD coding, I was able to code the add and view function, but I'm having a hard time with the edit and delete function.
I have 4 files, the master blade file, the web.php (routing), the blade file and the Form Controller.
This is the promo.blade.php file:
<table class="table table-striped" id="table1" >
<thead>
<tr>
<th class="text-center">ACTION</th>
<th class="text-center">Offer ID</th>
<th class="text-center">Promo Name</th>
<th class="text-center">Promo Price</th>
<th class="text-center">Status</th>
</tr>
</thead>
<tbody>
#foreach ($data as $key => $item)
<tr>
<td class="text-center">
<a href="#" data-bs-toggle="modal" data-bs-target="#show" data-myofferid="{{$item->offerId}}" data-mytitle="{{$item->promoName}}" data-myprice="{{$item->promoPrice}}">
<span class="badge bg-success"><i class="bi bi-eye-fill"></i></span>
</a>
<a href="#" data-bs-toggle="modal" data-bs-target="#edit" data-mainid="{{$item->id}}" data-myofferid="{{$item->offerId}}" data-mytitle="{{$item->promoName}}" data-myprice="{{$item->promoPrice}}">
<span class="badge bg-primary"><i class="bi bi-pencil-square"></i></span>
</a>
<a href="#" data-bs-toggle="modal" data-bs-target="#delete" data-myofferid="{{$item->offerId}}" data-mytitle="{{$item->promoName}}" data-myprice="{{$item->promoPrice}}">
<span class="badge bg-danger"><i class="bi bi-trash"></i></span>
</a>
</td>
<td class="date text-center">{{ $item->offerId }}</td>
<td class="date text-center">{{ $item->promoName }}</td>
<td class="number text-center">{{ $item->promoPrice}}</td>
<td class="number text-center">{{ $item->isActive }}</td>
</tr>
#endforeach
</tbody>
</table>
<!--Start Modal Edit -->
<div class="modal fade text-left" id="edit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel160" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" role="document">
<div class="modal-content">
<div class="modal-header bg-primary">
<h5 class="modal-title white" id="add">
Edit Promo
</h5>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
<i data-feather="x"></i>
</button>
</div>
<div class="modal-body">
<form action="{{ route('promo.edit') }}" method="POST">
#csrf
<div class="form-group">
<label for="">ID</label>
<input type="text" class="form-control" name="id" id="id" value="">
<span style="color:red">#error('id'){{$message}} #enderror</span>
</div>
<div class="form-group">
<label for="">Offer ID</label>
<input type="text" class="form-control" name="offerId" id="offerId" value="">
<span style="color:red">#error('offerId'){{$message}} #enderror</span>
</div>
<div class="form-group">
<label for="">Promo Name</label>
<input type="text" class="form-control" name="promoName" id="promoName" value="">
<span style="color:red">#error('promoName'){{$message}} #enderror</span>
</div>
<div class="form-group">
<label for="">Promo Price</label>
<input type="number" class="form-control" name="promoPrice" id="promoPrice" value="">
<span style="color:red">#error('promoPrice'){{$message}} #enderror</span>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light-secondary" data-bs-dismiss="modal">
<i class="bx bx-x d-block d-sm-none"></i>
<span class="d-none d-sm-block">CANCEL</span>
</button>
<button type="submit" class="btn btn-primary ml-1">
<i class="bx bx-check d-block d-sm-none"></i>
<span class="d-none d-sm-block">SAVE</span>
</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- End Modal Edit-->
Then this is the web.php file, for the routing:
Route::get('promo.promo', [App\Http\Controllers\FormControllerPromo::class, 'viewRecord'])->middleware('auth')->name('promo.promo');
Route::post('promo.add', [App\Http\Controllers\FormControllerPromo::class, 'addPromo'])->name('promo.add');
Route::post('promo.delete/{id}', [App\Http\Controllers\FormControllerPromo::class, 'viewDelete'])->middleware('auth');
Route::get('promo.edit', [App\Http\Controllers\FormControllerPromo::class, 'viewRecord'])->middleware('auth')->name('promo.edit');
Route::get('promo.edit/{id}', [App\Http\Controllers\FormControllerPromo::class, 'viewDetail'])->middleware('auth');
Route::post('promo.edit', [App\Http\Controllers\FormControllerPromo::class, 'edit'])->name('promo.edit');
This is the master.blade.php file:
<!--Start Modal edit for Promo-->
<script type="text/javascript">
$('#edit').on('show.bs.modal', function (event){
var button = $(event.relatedTarget)
var mainid = button.data('mainid')
var id = button.data('myofferid')
var title = button.data('mytitle')
var price = button.data('myprice')
var modal = $(this)
modal.find('.modal-body #id').val(mainid);
modal.find('.modal-body #offerId').val(id);
modal.find('.modal-body #promoName').val(title);
modal.find('.modal-body #promoPrice').val(price);
})
</script>
<!--End Modal edit for Promo-->
I think this is the part where the code wont execute properly.
This is the FormControllerPromo.php file:
// view form
public function index()
{
return view('promo.promo');
}
// view record
public function viewRecord()
{
$data = DB::table('promo')->get();
return view('promo.promo',compact('data'));
}
// view detail
public function viewDetail($id)
{
$data = DB::table('promo')->where('id',$id)->get();
return view('promo.promo',compact('data'));
}
// edit promo
public function edit(Request $request){
$id = $request->input('id');
$offerId = $request->input('offerId');
$promoName = $request->input('promoName');
$promoPrice = $request->input('promoPrice');
DB::table('promo')
->where('id', $id) // find your user by their email
->limit(1) // optional - to ensure only one record is updated.
->update(array('offerId' => $offerId, 'promoName' => $promoName, 'promoPrice' => $promoPrice)); // update the record in the DB.
$data = DB::table('promo');
return view('promo.promo',compact('data'));
}
I've been trying to code this for almost a week now with no success, any help is highly appreciated. :)
the update seems right, should work. but when you pass the $data variable to your view, you should call ->get(), because otherwise you return a query builder instance, that later raises the Undefined property error when trying to access {{$item->offerId}}.
change second last line in your example
//from this:
$data = DB::table('promo');
//to this:
$data = DB::table('promo')->get();
//or to this if you want to show only one record:
$data = DB::table('promo')->where('id', $id)->get();

How to retain the values in input fields when form submit fails in Laravel

I have this code in Laravel-5.8. There are two models:
class HrLeaveType extends Model
{
protected $table = 'hr_leave_types';
protected $primaryKey = 'id';
protected $fillable = [
'leave_type_name',
'leave_type_code',
'description',
];
public function leavetypedetail()
{
return $this->hasMany('App\Models\Hr\HrLeaveTypeDetail');
}
}
class HrLeaveTypeDetail extends Model
{
protected $table = 'hr_leave_type_details';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'leave_type_id',
'company_id',
'employee_type_id',
'no_of_days',
];
protected $casts = [
'data' => 'array',
];
public function leavetype()
{
return $this->belongsTo('App\Models\Hr\HrLeaveType', 'leave_type_id', 'id');
}
public function employeetype()
{
return $this->belongsTo('App\Models\Hr\HrEmployeeType', 'employee_type_id', 'id' );
}
}
Request Rules
public function rules()
{
return [
'leave_type_name' => [
'required',
'string',
'min:3',
'max:80',
Rule::unique('hr_leave_types')->where(function ($query) {
return $query->where('leave_type_name', $this->leave_type_name)
->where('company_id', $this->company_id);
})
],
'leave_type_code' => [
'nullable',
'string',
'max:10',
Rule::unique('hr_leave_types')->where(function ($query) {
return $query->where('leave_type_code', $this->leave_type_code)
->where('company_id', $this->company_id);
})
],
'no_of_days' => 'required|array',
'no_of_days.*' => [
'required',
'numeric',
'max:120'
],
'employee_type_id' => 'required|array',
'employee_type_id.*' => [
'required',
],
];
}
}
Controller
public function create()
{
$userCompany = Auth::user()->company_id;
$employeetypes = HrEmployeeType::where('company_id', $userCompany)->get();
$leavetype = new HrLeaveType();
return view('leave.leave_types.create')
->with('leavetype', $leavetype)
->with('employeetypes', $employeetypes);
}
public function store(StoreLeaveTypeRequest $request)
{
$userCompany = Auth::user()->company_id;
$leavetype = new HrLeaveType();
$leavetype->leave_type_name = $request->leave_type_name;
$leavetype->leave_type_code = $request->leave_type_code;
$leavetype->description = $request->description;
$leavetype->save();
foreach ($request->employee_type_id as $key => $employee_type_id){
$insert_array = [
'no_of_days' => $request->no_of_days[$key],
'employee_type_id' => $request->employee_type_id[$key],
'leave_type_id' => $leavetype->id,
];
HrLeaveTypeDetail::create($insert_array );
}
Session::flash('success', 'Leave Type is created successfully');
return redirect()->route('leave.leave_types.index');
}
}
LeaveTypeDetail is dynamically created
create.blade
#if (Session::has('error'))
<div class="alert alert-warning" align="left">
×
<strong>!</strong> {{Session::get('error')}}
</div>
#endif
<br>
#include('partials._messages')
<form action="{{route('leave.leave_types.store')}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{csrf_field()}}
<div class="card-body">
<div class="form-body">
<div class="row">
<div class="col-12 col-sm-6">
<div class="form-group">
<label class="control-label"> Leave Type Name:<span style="color:red;">*</span></label>
<input type="text" name="leave_type_name" value="{{ old('leave_type_name', $leavetype->leave_type_name) }}" placeholder="Enter leave type name" class="form-control #error('leave_type_name') is-invalid #enderror">
#error('leave_type_name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="col-12 col-sm-6">
<div class="form-group">
<label class="control-label"> Leave Type Code:</label>
<input type="text" name="leave_type_code" value="{{ old('leave_type_code', $leavetype->leave_type_code) }}" placeholder="Enter leave typecode" class="form-control #error('leave_type_code') is-invalid #enderror">
#error('leave_type_code')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<label>Description</label>
<textarea rows="2" name="description" class="form-control #error('description') is-invalid #enderror" value="{{old('description',$leavetype->description)}}" placeholder="Enter Description here ...">{{old('description',$leavetype->description)}}</textarea>
#error('description')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="col-sm-12">
<table class="table table-bordered">
<thead>
<tr>
<th scope="col">Employee Type<span style="color:red;">*</span></th>
<th scope="col">Leave Days<span style="color:red;">*</span></th>
<th scope="col"><a class="btn btn-info addRow"><i class="fa fa-plus"></i></a></th>
</tr>
</thead>
<tbody>
<tr>
<td width="60%">
<option value="0" selected="true" disabled="true">Select Employee Type</option>
#if($employeetypes->count() > 0 )
#foreach($employeetypes as $employeetype)
<option name="employee_type_id[]" value="{{$employeetype->id}}">{{$employeetype->employee_type_name}}</option>
#endforeach
#endif
</select>
</td>
<td width="35%"><input type="text" name="no_of_days[]" placeholder="Enter leave days here" class="form-control no_of_days" max="120"></td>
<td width="5%"><a class="btn btn-danger remove"> <i class="fa fa-times"></i></a></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary">{{ trans('global.save') }}</button>
<button type="button" onclick="window.location.href='{{route('leave.leave_types.index')}}'" class="btn btn-default">Cancel</button>
</div>
</form>
<script type="text/javascript">
$(document).ready(function(){
$('.addRow').on('click', function () {
addRow();
});
function addRow() {
var addRow = '<tr>\n' +
' <td width="60%"><select class="form-control select2bs4" data-placeholder="Choose Employee Type" tabindex="1" name="employee_type_id[]">\n' +
' <option value="0" selected="true" disabled="true">Select Employee Type</option>\n' +
' #if($employeetypes->count() > 0 )\n' +
' #foreach($employeetypes as $employeetype)\n' +
' <option value="{{$employeetype->id}}">{{$employeetype->employee_type_name}}</option>\n' +
' #endforeach\n' +
' #endif\n' +
' </select></td>\n' +
' <td width="35%"><input type="text" name="no_of_days[]" placeholder="Enter leave days here" class="form-control no_of_days" max="120"></td>\n' +
' <td width="5%"><a class="btn btn-danger remove"> <i class="fa fa-times"></i></a></td>\n' +
' </tr>';
$('tbody').append(addRow);
addRemoveListener();
};
addRemoveListener();
});
</script>
One leave type has many leave type details. For the controller and view, I have dynamic form input.
leave_type_details are arrays.
When user submits, if action fails all the fields should retail their values. This happens to only leave_type, but leave_type_details fields did not retain their values. It clears off.
How do I achieve this?
Thanks
in blade :
#if(old('input_name'))
#foreach(old('input_name') as $key => $value)
<your_html>{{old("input_name.{$key}"}}</your_html>
#endforeach
#endif

How to pass array data from vuejs to laravel api controller

I want to make an invoice system with laravel using vuejs by api. Firstly show all product and when i click add to cart it added.
Here is the screenshot:
Now i want to send input fill data to order_masters table and including last inserted ID cart data send order_details table.
but i cant not pass the whole data. sometime pass customer information but not cart data.
N. B: I am using vuejs, vform and API
My component code is given below:
<template>
<div class="row">
<div class="col-md-7">
<div class="col-md-11">
<input type="hidden" v-model="field">
<input type="search" v-model="query" class="form-control form-control-sm mb-3" placeholder="Search Here">
</div>
<div class="row justify-content-center">
<div v-show="products.length" v-for="(product, id) in products" :key="id" class="card col-xl-3 col-md-3 col-sm-3 mb-5 mr-5 float-left" style="background-color:lightgray">
<div class="card-body">
<h5 class="card-title">{{product.name}}</h5>
<p class="card-text"><input type="text" v-model="product.qty" class="form-control form-control-sm mb-2"></p>
<strong class="">
{{product.price}} TK
</strong>
<button class="btn btn-sm btn-primary float-right" #click="addToCart(product)">
<i class="fas fa-plus"></i>
</button>
</div>
</div>
</div>
<div v-show="!products.length" class="alert alert-danger text-center" role="alert">
<strong>Opps! No Data Found!</strong>
</div>
<pagination v-if="pagination.last_page > 1" :pagination="pagination" :offset="5" #paginate="query === ''? showProduct(): searchProduct()"></pagination>
</div>
<div class="col-md-5 float-righ">
<form #submit.prevent="store" #keydown="form.onKeydown($event)">
<alert-error :form="form"></alert-error>
<div class="row mb-2">
<label for="" class="col-md-3 font-weight-bold">Name</label>
<div class="col-md-9">
<input type="text" v-model="form.name" name="name" class="form-control form-control-sm" :class="{ 'is-invalid': form.errors.has('name') }">
<has-error :form="form" field="name"></has-error>
</div>
</div>
<div class="row mb-2">
<label for="" class="col-md-3 font-weight-bold">Phone</label>
<div class="col-md-9">
<input type="text" v-model="form.phone" name="phone" class="form-control form-control-sm" :class="{ 'is-invalid': form.errors.has('phone') }">
<has-error :form="form" field="phone"></has-error>
</div>
</div>
<div class="row mb-2">
<label for="" class="col-md-3 font-weight-bold">Address</label>
<div class="col-md-9">
<input type="text" v-model="form.address" name="address" class="form-control form-control-sm" :class="{ 'is-invalid': form.errors.has('address') }" >
<has-error :form="form" field="address"></has-error>
</div>
</div>
<div class="mb-5">
<input type="button" class="btn btn-sm btn-danger float-left" #click="clearCart" value="Clear" />
<button type="submit" :disabled="form.busy" class="btn btn-sm btn-success float-right" #click="store">Checkout</button>
</div>
<table class="table table-sm table-bordered table-striped">
<thead class="text-center">
<tr>
<th>ID</th>
<th>Name</th>
<th>Qty</th>
<th>Price</th>
<th>L/T</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr v-for="(cart, i) in carts" :key="i">
<td class="text-center"><input type="hidden" name="pro_id[]" v-model="form.pro_id"> {{cart.id}}</td>
<td>{{cart.name}} </td>
<td class="text-right" name="qty"><input type="hidden" name="qty[]" v-model="form.qty">{{cart.qty}}</td>
<td class="text-right" name="unit_price"><input type="hidden" name="pro_id[]" v-model="form.price">{{cart.price}}</td>
<td class="text-right">{{cart.price*cart.qty}}</td>
<td class="text-center"><button type="button" #click="removeProduct(i)" class="btn btn-sm btn-danger">x</button></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="4" class="text-right font-weight-bold">Total =</td>
<td class="text-right"> {{total}}/-</td>
</tr>
</tfoot>
</table>
</form>
</div>
<vue-progress-bar></vue-progress-bar>
<vue-snotify></vue-snotify>
</div>
<script>
export default {
data(){
return{
field: 'name',
query: '',
form: new Form({
'name': '',
'phone': '',
'address':'',
'pro_id' : [],
'qty' : [],
'unit_price' : []
}),
products:[],
carts:[],
pagination:{
current_page: 1
}
}
},
methods:{
store(){
var data = {
carts: this.carts,
}
this.$Progress.start()
this.form.busy = true
this.form.post('api/pos', data)
.then( res => {
this.form.reset()
this.form.clear()
this.$Progress.finish()
console.log(data)
})
.catch( e => {
this.$Progress.fail()
console.log(e)
})
}
}
}
</script>
Here is API Controller Function:
public function store(Request $request)
{
$carts = json_decode($request->getContent('data'), true);
$this->validate($request,[
'name' => 'required',
'phone' => 'required',
'address' => 'required'
]);
$order = new OrderMaster;
$order->name = $request->name;
$order->phone = $request->phone;
$order->address = $request->address;
$order->save();
$order_id = DB::getPdo()->lastInsertId();
foreach ($carts as $cart) {
OrderDetails::create([
'order_id' => $order_id,
'product_id' => ?,
'qty' => ?,
'unite_price' => ?,
]);
}
}
First, you're calling form.post wrong. Second parameter is not additional data, but config options for axios.request call.
In order to send carts array you should add it to the form itself:
form: new Form({
'name': '',
'phone': '',
'address':'',
'pro_id' : [],
'qty' : [],
'unit_price' : [],
'carts' : [], // <-- added
}),
Then, replace usage of carts with form.carts in your template (and methods).
Now, carts will be sent to the server along with other data.
And lastly, you don't need to use json_decode at all.
//...
$data = $this->validate($request, [
'name' => 'required',
'phone' => 'required',
'address' => 'required',
'carts' => 'required|array',
'carts.*.name' => 'string',
'carts.*.id' => 'integer',
'carts.*.qty' => 'integer',
'carts.*.price' => 'numeric',
]);
Then, you can use $data as a source of data.
foreach ($data['carts'] as $cart) {
OrderDetails::create([
'order_id' => $order_id,
'product_id' => $cart['id'],
'qty' => $cart['qty'],
'unite_price' => $cart['price'],
]);
}
I had been done it in other way. Not using vform i used axios. but i want to done it using vform.
return{
field: 'name',
query: '',
form:{
'name': '',
'phone': '',
'address':''
},
products:[],
carts:[],
pagination:{
current_page: 1
}
}
store(){
let client = {
cli: this.form
}
let data = {
carts: this.carts
}
this.$Progress.start()
axios.post('api/pos', {data, client})
.then( res => {
this.$Progress.finish()
console.log(res)
})
.catch( e => {
this.$Progress.fail()
console.log(e)
})
}
Controller:
$carts = json_decode($request->getContent('client','data'), true);
$customer = $carts['client'];
$pro_info = $carts['data'];
foreach ($customer as $cus) {
$order = new OrderMaster;
$order->name = $cus['name'];
$order->phone = $cus['phone'];
$order->address = $cus['address'];
$order->save();
}
$order_id = DB::getPdo()->lastInsertId();
foreach ($pro_info as $cart) {
foreach ($cart as $c) {
OrderDetails::create([
'order_id' => $order_id,
'product_id' => $c['id'],
'qty' => $c['qty'],
'unit_price' => $c['price'],
]);
}
}

Getting error while clicking on edit function button in laravel

I need to edit by data from database via my admin panel. So i created table with clickable button for edit function.
Now when I click on edit button, I am seeing ID number at bottom but getting sorry page couldn't found error ! I have double checked all controller, route and everything. It seems all good, but I don't know what's the error!
Route Code:
Route::get('/admin/baseFare',[
'uses' => 'ExtraBaseFareController#basefare',
'as' => 'base.fare'
]);
Route::get('/admin/baseFare/edit/{$id}',[
'uses' => 'ExtraBaseFareController#editBaseFare',
'as' => 'editbase.fare'
]);
Route::post('/admin/baseFare/update/{id}', [
'uses' => 'ExtraBaseFareController#baseFareUpdate',
'as' => 'base.fareupdate'
]);`
Controller Code:
public function basefare()
{
$base = BaseFare::all();
return view('Admin.BaseFare.index')->With('base', $base);
}
public function editBaseFare($id)
{
$base = BaseFare::find($id);
return view('Admin.BaseFare.editBaseFare')->with('base', $base);
}
public function baseFareUpdate(Request $request, $id)
{
$base = BaseFare::find($id);
$base->fareinpercentage = $request->fareinpercentage;
$base->fareinrupees = $request->fareinrupees;
$base->save();
Session::flash('success','Base fare successfully updated');
return redirect()->route('base.fare');
}
Index Page code:
<table class="table display nowrap table-striped table-bordered bootstrap-3 scroll-horizontal">
<thead>
<tr>
<th>S.No</th>
<th>Fare in Percentage (%)</th>
<th>Fare in Rupees (Rs)</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
#php $number = 1; #endphp
#foreach($base as $base)
<tr>
<td>
{{ $number.'.' }}
#php $number++; #endphp
</td>
<td>{{ $base->fareinpercentage }}</td>
<td>{{ $base->fareinrupees }}</td>
<td>
<a href="{{ route('editbase.fare',['id' => $base->basefareid ]) }}" class="m-portlet__nav-link btn m-btn m-btn--hover-accent m-btn--icon m-btn--icon-only m-btn--pill" title="Edit ">
<i class="la la-edit"></i>
</a>
</td>
</tr>
#endforeach
</tbody>
</table>`
Edit Page Code:
<form class="form" method="post" action="{{ route('base.fareupdate',['id' => $base->basefareid ]) }}">
<div class="form-body">
<h4 class="form-section"><i class="la la-eye"></i>Base Fare Controller</h4>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="userinput2">Fare in Percentage (%)</label>
<input type="text" id="fareinpercentage" value="{{ $base->fareinpercentage }}" class="form-control border-primary" name="fareinpercentage">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="userinput3">Fare in Rupee (Rs)</label>
<input type="text" id="fareinrupees" value="{{ $base->fareinrupees }}" class="form-control border-primary" name="fareinrupees">
</div>
</div>
</div>
</div>
<div class="form-actions right">
<button type="button" class="btn btn-warning mr-1">
<i class="ft-x"></i> Cancel
</button>
<button type="submit" name="submit" class="btn btn-primary">
<i class="la la-check-square-o"></i> Save
</button>
</div>
</form>`
These are the codes, the kindly help me to find our the error, The main function is to edit the field from database!
If I understand the question correctly you can't go to the edit page.
Run 'php artisan route:list' and compare the routes.
And I can't figure out why you have dollar sign before the id in the route.

how to solve this error in laravel: ErrorException (E_WARNING) Invalid argument supplied for foreach()

I am creating a medicine shop invoice system . So at that process, I am creating a invoice form where customer information and invoicing information store in a two different model Customer model and Invoice model.
My invoice form view code below;
<form action="{{url('/invoice')}}" method="post">
{{csrf_field()}}
<div class="form-row">
<div class="col-md-4 col-md-offset-2">
<label for="customerName">Customer Name:</label>
<input type="text" id="customerName" name="customerName" class="form-control"><br>
<label for="address"> Address:</label>
<input type="text" id="address" name="address" class="form-control"><br>
<label for="mobile"> Mobile No.:</label>
<input type="text" id="mobile" name="mobileNumber" class="form-control"><br>
</div>
<div class="col-md-4">
<label for="invoiceNo"> Invoice No.:</label>
<input type="text" id="invoiceNo" name="invoiceNum" class="form-control"><br>
<label for="date"> Date:</label>
<input type="date" id="date" name="date" class="form-control"><br>
</div>
</div>
<hr>
<table class="table table-bordered" cellpadding="10px" cellspacing="5px">
<thead>
<th>Meidicine Name:.</th>
<th>Quantity</th>
<th>Price</th>
<th>Total Price</th>
<th style="text-align: center"><i class="fas fa-plus-square plus "></i></th>
</thead>
<tbody>
<tr>
<td>
<select name="medicineName" id="" class="form-control-sm medicineName" >
#foreach($data as $item)
<option value="{{$item->id}}">{{$item->medicineName}}</option>
#endforeach
</select>
</td>
<td><input type="number" class="form-control-sm quantity" name="quantity"></td>
<td><input type="number" class="form-control-sm price" name="price"></td>
<td><input type="number" class="form-control-sm totalAmount" name="totalAmount"></td>
<td style="text-align: center"><i class="fas fa-times"></i></td>
</tr>
<tr><td><input type="submit" class="btn btn-info btn-sm" value="ADD"></td></tr>
</tbody>
</table>
</form>
In this invoice form medicine name came from another model Medicine using laravel eloquent relationship
my InvoiceController store method code below
public function store(Request $request)
{
$customer = new Customer();
$customer->fill($request->all());
if($customer->save()){
$id = $customer->id;
foreach($request->medicineName as $value => $key) --->error occurs
this line
{
$data = array(
'customer_id' => $id,
'medicine_id' => $value,
'invoiceNum' => $request->invoiceNum[$key],
'date' =>$request->date[$key],
'quantity' =>$request->quantity[$key],
'price' =>$request->price[$key],
'totalAmount'=> $request->totalAmount[$key]
);
Invoice::insert($data);
}
}
return back();
}
when I click ADD button to submit data two different model Customer & Invoice browser can show error look like
"ErrorException (E_WARNING)
Invalid argument supplied for foreach()"
How to solve this type of error, pls anyone can help me..
it's because $request->medicineName is just one element and not an array or collection, try it like this :
public function store(Request $request)
{
$customer = new Customer();
$customer->fill($request->all());
if($customer->save()){
$id = $customer->id;
$data = array(
'customer_id' => $id,
'medicine_id' => $request->medicineName,
'invoiceNum' => $request->invoiceNum,
'date' =>$request->date,
'quantity' =>$request->quantity,
'price' =>$request->price,
'totalAmount'=> $request->totalAmount
);
Invoice::insert($data);
}
return back();
}

Resources