Unable to edit data on the same view page laravel - javascript

I want to update the business hour on the same page. There are other answer that I review in the stackoverflow but I still cannot manage. Help really appreciated.
Model
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Hour extends Model
{
public $table = 'biz_hour';
protected $primaryKey = 'day_id';
protected $fillable = [
'day_id', 'day_name', 'start_time', 'end_time', 'day_off'
];
public $timestamps = false;
}
Controller
public function update(Request $request, Hour $biz_hour)
{
$request->validate([
'start_time' => 'required',
]);
$start_time = \App\Models\Hour::find($biz_hour);
['start_time' => $request->start_time];
foreach($biz_hour as $biz_hour){
$start_time->save();
}
return redirect('start_time');
//$biz_hour->update($request->all());
//return redirect()->route('biz_hour.index');
}
Biz_hour.blade.php
<div class="table-responsive">
<table class="table">
<thead class="text-uppercase">
<tr>
<th scope="col">Day</th>
<th scope="col">Start Time</th>
<th scope="col">End Time</th>
<th scope="col">is Day off?</th>
</tr>
</thead>
#foreach($biz_hour as $biz_hour)
<form action="{{ route('biz_hour.update',$biz_hour->day_id) }}" method="POST">
#csrf
#method('PUT')
<tbody>
<tr>
<th scope="row"><br>{{$biz_hour->day_name}}</th>
<td><div class="form-group">
<input class="form-control" type="time" value={{ Carbon::parse($biz_hour->start_time)->format('h:i') }} name="start_time"></div>
</td>
<td><div class="form-group">
<input class="form-control" type="time" value={{$biz_hour->end_time}} name="end_time"></div>
</td>
<td><br><label class="switch">
<input type="checkbox">
<span class="slider round"></span>
</label></td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
<div class="main-content-inner">
<div class="col-lg-6 mt-5">
<button type="submit" class="btn btn-primary mb-3" name="upload">Save</button>
</div>
</div>
</form>
After clicking save button, the page only refresh but the data is not sent to the database. Thanks in advance.

Update is not done because you actually didn't assign the new start_time for the start_time you wanted to update.
Try this
public function update(Request $request, Hour $biz_hour)
{
$request->validate([
'start_time' => 'required',
]);
$start_time = \App\Models\Hour::find($biz_hour);
$start_time->start_time => $request->start_time;
foreach($biz_hour as $biz_hour){
$start_time->save();
}
return redirect()->back()->with('status', 'updated');
}

Related

Validation error for multiple input field Laravel 8

I have a validation problem regarding multiple input fieldL to store in the database. When I submit, the errors show "additional mark field is required." I try to test dd($request) but the attributes is null. How can I store in DB with multiple input fields?
Controller
public function StoreAdditionalProcuments(Request $request)
{
$request->validate([
'additional_remark' => 'required',
]);
foreach ($request->addmore as $key => $value) {
$input = $request->all();
$input['additional_remark'] = $value['additional_remark'];
AssetProcument::create($input);
}
return redirect('asset')->with('success', 'Maklumat Aset berjaya disimpan.');
}
AssetProcument.php Model
class AssetProcument extends Model
{
public $fillable = [
'additional_remark',
];
Blade
<form action="{{ route('asset_store_additional_procument') }}" method="POST">
#csrf
<div class="card-body">
<div class="col">
<table class="table table-bordered" id="dynamicTable">
<thead>
<tr>
<th>Catatan</th>
</tr>
</thead>
<tbody>
<tr>
<td style="width:50%"><textarea type="text" name="addmore[][additional_remark]"
class="form-control"></textarea></td>
<td>
<button type="button" name="add" id="add" class="btn btn-success">Tambah</button>
</td>
</tr>
</body>
</table>
</div>
<div class="col-12">
<input type="submit" value="Save Changes" class="btn btn-success float-right">
</div>
</div>
</form>
<script type="text/javascript">
var i = 0;
$("#add").click(function(){
++i;
$("#dynamicTable").append('<tr><td><textarea type="text" name="addmore['+i+'][additional_remark]" class="form-control" /></textarea></td>'.'
<td><button type="button" class="btn btn-danger remove-tr">Remove</button></td></tr>');
});
$(document).on('click', '.remove-tr', function(){
$(this).parents('tr').remove();
});
Route
Route::post('asset_store_additionalprocuments',[AssetController::class,'StoreAdditionalProcuments'])->name('asset_store_additional_procument');
Since additional_remark input is addmore[][additional_remark], your validation should be like this
$request->validate([
'addmore.*.additional_remark' => 'required',
]);
* mark is all indexes of addmore array

How to insert multiple data into the database using a single method

As the title suggests, I would like to insert data into 03 tables (products, products_order, orders).
Indeed, I would like
1- I want to recover the stock_products and subtract from the order's quantity of products (stock_actuel = stock_actuel - quantity)
2- In the products_order table, we record the identifier the product identifier with the price of each product, the quantity and the total amount.
3-In the order table, we record the order informations such as number, dates etc.
All this in a single store or create.
here is what i did and it doesn't work.
public function store(Request $request, $id)
{
// update stockproduit
// $stockproduit = Produits::find($id);
$produits = collect($request->produits->stockproduit)->transform(function ($stockproduit){
$stockproduit['stock_actuel'] = $stockproduit['stock_actuel'] - $stockproduit['quantity'];
$stockproduit->update();
});
$commande = new RestauCommande;
$commande->produit_id = 'cmde-' .$id;
$produits = collect($request->produits)->transform(function ($produit) {
$produit['total'] = $produit['quantity'] * $produit['prix'];
return new CommandesProduits($produit);
});
$data = $request->except('produits');
// $data->made_by = $request->get('users_id');
// $data->tables_id = $request->get('users_id');
$data['sub_total'] = $produits->sum('total');
$data['grand_total'] = $data['sub_total'] - $data['remise'];
// $data['clients_id'] = $client->id->$request->get('clients_id');
$data = RestauCommande::create($data);
$commande->produits()->saveMany($produits);
return response()
->json([
'La Commande a été créée avec succès' => true,
'id' => $commande->id,
]);
}
My vue
<b-modal
id="modalShow"
title="Commandes"
ref="myModalRefProduit"
hide-footer
size="lg"
>
<div>
<div class="container mt-12">
<div class="row col-md-14">
<form #submit.prevent="store" enctype="multipart/form-data">
<div class="col-md-12 mx-auto">
<table
class="table table-responsive rounded table-striped table-sm"
>
<thead>
<tr>
<th scope="col">#</th>
<!-- <th scope="col"></th> -->
<th scope="col">Produit</th>
<th scope="col">Quantité</th>
<th scope="col">Prix</th>
<th scope="col">Total</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
<tr v-for="(produit, id) in cart" v-bind:key="produit.id">
<th scope="row">{{ id + 1 }}</th>
<td>
<input
class="form-control"
type="hidden"
placeholder=""
v-model="users_id"
required
autofocus
/>
</td>
<td>{{ produit.nom }}</td>
<td>
<center>{{ produit.quantity }}</center>
</td>
<td>{{ produit.prix }}</td>
<td>{{ produit.quantity * produit.prix }}</td>
<td>
<div class="cart-icons">
<button v-on:click="cartPlusOne(produit)">
<i class="fa fa-plus"></i>
</button>
<button v-on:click="cartMinusOne(produit, id)">
<i class="fa fa-minus"></i>
</button>
<button
v-on:click="cartRemoveItem(id)"
title="supprimer le produit"
>
<i class="fa fa-trash"></i>
</button>
</div>
</td>
</tr>
<tr class="font-weight-bold">
<td style colspan="4" align="right">Total</td>
<td>{{ cartTotalAmount }}</td>
</tr>
</tbody>
</table>
<div class="container">
<div class="row">
<div class="col-md-4 pl-0">
<b-button
v-on:click="store()"
variant="outline-success btn-sm btn-block"
>Valider</b-button
>
</div>
<div class="col-md-4 pr-0">
<b-button
v-on:click="$refs.myModalRefProduit.hide()"
variant="outline-dark btn-sm btn-block"
>Annuler</b-button
>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<center></center>
</b-modal>
the script
store() {
// alert ('test')
const data = new FormData();
data.append(
"made_by",
document.querySelector("meta[name='users_id']").getAttribute("content")
);
axios
.post("/api/commander", data )
.then((response) => {
this.produits = response.data;
// this.loading = false;
// this.form.reset();
// window.location = response.data.redirect;
})
// .then(location.reload())
.catch(function (error) {
console.log(error);
});
},
This is the error i get
Error: Request failed with status code 405
Thank you in advance.

Defer in my app.js in laravel is not letting my javascript code work

Even though I have my entire code in javascript until I remove the defer from my app.js it does not work. Is there a reason for it?
Edit
I added my whole blade.php file here the javascript in at the bottom is being extended from my add.blade.php file. The javascript code is also yielded from my add.blade.php file.
Here is my blade file
#extends('layouts.app')
#section('style')
<link href="{{ asset('css/Admin/sql-data-viewer.css') }}" rel="stylesheet">
#endsection
#section('content')
<?php ?>
<section class="data-viewer">
<div class="d-flex justify-content-between px-3">
<h3>Select Banner to change</h3>
<button type="button" class="btn add-data text-white rounded-pill">Add Banner <i class="fas fa-plus"></i></button>
</div>
<form method="post">
#csrf
#method('DELETE')
#if(session()->has('message'))
<div class="alert alert-success">
{{ session()->get('message') }}
</div>
#endif
<div class="delete pl-3 mt-3 mb-3">
<label for="deleteSelected">Action:</label>
<select name="deleteSelected" id="deleteSelected" class="#error('deleteSelected') is-invalid #enderror" name="deleteSelected" >
<option disabled selected>---------</option>
<option>Delete Selected Banner</option>
</select>
<button formaction="{{ route('banners.delete') }}" type="submit" class="go" id="deleleGo" onclick="deleteBtn()">Go</button>
<span id="selected">0</span> of {{$showCounts}} selected
#error('deleteSelected')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<table class="table table-hover table-striped table-dark">
<div id="selectError"><p>You must check at least one checkbox</p></div>
<thead>
<tr>
<th scope="col"><input type="checkbox" id="checkHead" class="selectall"></th>
<th scope="col">Id</th>
<th scope="col">Image</th>
<th scope="col">Caption Heading</th>
<th scope="col">Caption Description</th>
</tr>
</thead>
<tbody>
#foreach ($banners as $banner)
<tr>
<th scope="row"><input type="checkbox" name="ids[]" class="selectbox" value="{{ $banner->id }}" onchange="change()"></th>
<td onClick="location.href='{{URL::current()}}/{{Str::slug($banner->id) }}/edit'" style="cursor: pointer">{{$banner->id}}</td>
<td onClick="location.href='{{URL::current()}}/{{Str::slug($banner->id) }}/edit'" style="cursor: pointer"><img src="/storage/{{$banner->Banner_Image}}" alt="{{$banner->Caption_Heading}}" class="img-thumbnail" width="70px" height="100px"></td>
<td onClick="location.href='{{URL::current()}}/{{Str::slug($banner->id) }}/edit'" style="cursor: pointer">{{$banner->Caption_Heading}}</td>
<td onClick="location.href='{{URL::current()}}/{{Str::slug($banner->id) }}/edit'" style="cursor: pointer">{{$banner->Caption_Description}}</td>
</tr>
#endforeach
</tbody>
</table>
</form>
</section>
#endsection
#section('script')
<script>
const all = document.getElementById("checkHead");
all.addEventListener('click',toogle);
function toogle() {
const isChecked = all.checked;
Array.from(document.getElementsByTagName('input')).forEach(element =>{
element.checked = isChecked;
});
}
function change(){
var total = document.getElementsByClassName('selectbox').length;
var number = document.querySelectorAll('.selectbox:checked').length;
if(total === number){
document.getElementById("checkHead").checked = true;
} else{
document.getElementById("checkHead").checked = false;
}
document.getElementById("selected").innerHTML = number;
}
function deleteBtn(){
checked = document.querySelectorAll("input[type=checkbox]:checked").length;
if(!checked) {
var a = document.getElementById("selectError").style.display = "block";
return false;
}
};
</script>
#endsection
It is probably happening because you are trying to get an element which is not there at the time this script runs. Make sure you include the javascript on bottom of the page if you don't want to defer it.

Vue router get value from vue router link

I have a list here from my table. It has a edit button and if I click edit button, It goes to another component which is called editTeacher. My question is how could I get the data from the table and transfer it to my editTeacher component. I get the data from route using axios . In laravel it is like this
<span class="glyphicon glyphicon-pencil"> .
How could I achieve it in vue?
Here is my code snippet
<table id="myTable" class="table table-hover">
<tbody>
<tr>
<th>ID</th>
<th>Image</th>
<th>First Name</th>
<th>Last Name</th>
<th>Gender</th>
<th>Birthday</th>
<th>Age</th>
<th>Type</th>
<th>Department</th>
<th>Status</th>
<th>Actions</th>
</tr>
<tr v-for="teacher in teachers" :key="teacher.id">
<td>{{teacher.id}}</td>
<td><img style=" border-radius: 50%;" :src="'img/'+teacher.image" height="42" width="42"/></td>
<td>{{teacher.firstname}}</td>
<td>{{teacher.lastname}}</td>
<td>{{teacher.gender}}</td>
<td>{{teacher.birthday}}</td>
<td>{{teacher.age}}</td>
<td>{{teacher.type}}</td>
<td>{{teacher.department_name}}</td>
<td v-if="teacher.status == 1"><span class="label label-success">Active</span></td>
<td v-else><span class="label label-danger">Inactive</span></td>
<td><router-link to="/viewTeacher"> <i class="fa fa-edit"></i></router-link></td>
</tr>
</tbody>
</table>
Route
//Teachers
Route::get('/getTeachers','TeacherController#index');
Route::post('/addTeacher','TeacherController#store');
Route::put('/editTeacher/{id}','TeacherController#update');
app.js route
{ path: '/viewTeacher', component: require('./components/editTeacher.vue').default },
Please follow the below code for the Vue js edit method.
As per your git repo.
app.js route
{ path: '/viewTeacher/:id', component: require('./components/editTeacher.vue').default, name: viewTeacher},
Edit Button in Teachers.vue
<router-link :to="{name: 'viewTeacher', params: {id: teacher.id}}" class="btn btn-xs btn-default">Edit</router-link>
EditTeacher.vue component
<template>
<div class="row">
<div class="col-xs-3">
<div class="box">
<div class="box-tools">
<img style="border-radius: 50%;" src="" height="100" width="50">
</div>
</div>
</div>
<div class="col-xs-9">
<div class="box">
<form v-on:submit.prevent="saveForm()">
<div class="row">
<div class="col-xs-12 form-group">
<label class="control-label">Teacher first name</label>
<input type="text" v-model="teacher.firstname" class="form-control">
</div>
</div>
<div class="row">
<div class="col-xs-12 form-group">
<label class="control-label">Teacher Last name</label>
<input type="text" v-model="teacher.lastname" class="form-control">
</div>
</div>
<div class="row">
<div class="col-xs-12 form-group">
<button class="btn btn-success">Update</button>
</div>
</div>
</form>
</div>
</div>
</div>
</template>
<script>
export default {
mounted() {
let app = this;
let id = app.$route.params.id;
app.teacherId = id;
axios.get('/getTeacher/' + id)
.then(function (resp) {
app.teacher = resp.data;
})
.catch(function () {
alert("Could not load teacher")
});
},
data: function () {
return {
teacherId: null,
teacher: {
firstname: '',
lastname: '',
}
}
},
methods: {
saveForm() {
var app = this;
var newTeacher = app.teacher;
axios.patch('/editTeacher/' + app.teacherId, newTeacher )
.then(function (resp) {
app.$router.replace('/');
})
.catch(function (resp) {
console.log(resp);
alert("Could not Update");
});
}
}
}
Web.php
Route::get('/getTeachers','TeacherController#index');
Route::get('/getTeacher/{id}','TeacherController#show');
Route::post('/addTeacher','TeacherController#store');
Route::put('/editTeacher/{id}','TeacherController#update');
Controller
public function show($id)
{
return Teacher::findOrFail($id);
}

List.js apply filter by default

I am a beginner in Javascript and would appreciate some guidance in using the List.js library. So far, I have created the filters and they are able to work. But I would like the default table to have filter 'Pending Delivery' applied already as this would be the most commonly accessed page.
HTML
(There is already code for the filters)
<table class="order-table table table-hover table-striped">
<thead>
<th>S/N</th>
<th>Order ID</th>
<th>Customer Name</th>
<th>Route Number</th>
<th>Order Date</th>
<th>Delivery Date</th>
<th>Status</th>
</thead>
<tbody class="list">
<tr>
<td>1</td>
<td class='orderId'>5</td>
<td>Matilda Tan</td>
<td>16</td>
<td>2018-06-29</td>
<td>2018-06-29</td>
<td class='sts'>Pending Delivery</td>
</tr>
<tr>
<td>2</td>
<td class='orderId'>7</td>
<td>Xena Yee</td>
<td>01</td>
<td>2018-06-21</td>
<td>2018-06-23</td>
<td class='sts'>Delivered</td>
</tr>
<div class="no-result">No Results</div>
<ul class="pagination"></ul>
</div>
</div>
</div>
JS
var options = {
valueNames: [
'name',
'sts',
{ data: ['status']}
],
page: 5,
pagination: true
};
var userList = new List('users', options);
function resetList(){
userList.search();
userList.filter();
userList.update();
$(".filter-all").prop('checked', true);
$('.filter').prop('checked', false);
$('.search').val('');
//console.log('Reset Successfully!');
};
function updateList(){
var values_status = $("input[name=status]:checked").val();
console.log(values_status);
userList.filter(function (item) {
var statusFilter = false;
if(values_status == "All")
{
statusFilter = true;
} else {
statusFilter = item.values().sts == values_status;
}
return statusFilter
});
userList.update();
//console.log('Filtered: ' + values_gender);
}
$(function(){
//updateList();
$("input[name=status]").change(updateList);
userList.on('updated', function (list) {
if (list.matchingItems.length > 0) {
$('.no-result').hide()
} else {
$('.no-result').show()
}
});
});
You have duplicated IDs. That's an error because an ID must be unique.
If you need to change from All to Pending Delivery selected it is enough to change your html moving the checked attribute from current position (All) to the Pending Delivery position.
After, call your updateList(); after the $("input[name=status]").change(updateList); in your dom ready function.
Your updated codepen
The short changes in your code:
$(function(){
//updateList();
$("input[name=status]").change(updateList);
updateList(); // this line added
userList.on('updated', function (list) {
if (list.matchingItems.length > 0) {
$('.no-result').hide()
} else {
$('.no-result').show()
}
});
});
<div class="container">
<div class="row">
<div id="users" class="col-xs-12">
<div class="filter-group row">
<div class="form-group col-xs-12 col-sm-12 col-md-4">
<input type="text" class="search form-control" placeholder="Search" />
</div>
<div class="form-group col-xs-12 col-sm-12 col-md-4">
<div class="radio-inline">
<label>
<input class="filter-all" type="radio" value="All"
name="status" id="status-all"/> All <!-- removed checked -->
</label>
</div>
<div class="radio-inline">
<label>
<input class="filter" type="radio"
value="Pending Delivery" name="status" id="status-pending" checked/>
Pending <!-- added checked -->
</label>
</div>
.......

Categories