insert multiple laravel checkbox datatable - laravel

I want to insert multi rows checked in my data table, when I click a button valider, everyone I have a problem in a laravel framework, I want to insert line check in a data table when click on button validate, this my code
the display of the salary list
<body>
<div class="container" id="app">
<div class="list-group">
<div class="list-group-item">
<h3>Pointage Mensuel</h3>
<div class="col-md-6 col-md-offset-3">
<h3>jour : {{$data['datek']}} chantier : {{$data['chantier_name']}}</h3>
</div>
<button class="btn btn-success add-all" data-url="">Valider Pointage de mois</button>
</div>
</div>
<div class="list-group">
<div class="list-group-item">
<table class="table table-bordered">
<tr>
<th>Archive</th>
<th><input type="checkbox" id="check_all"></th>
<th>S.No.</th>
<th>matricule</th>
<th>nom & prenom</th>
<th>salaire net</th>
<th>nbre de jour </th>
<th>prime</th>
</tr>
#if($salaries->count())
#foreach($salaries as $key => $salarie)
<tr id="tr_{{$salarie->id}}">
<td>archive</td>
<td><input type="checkbox" class="checkbox" data-id="{{$salarie->id}}"></td>
<td>{{ ++$key }}</td>
<td>{{ $salarie->matricule }}</td>
<td>{{ $salarie->nom }} {{ $salarie->prenom }}</td>
<td>{{ $salarie->salairenet }}</td>
<td><input type="text" name="nbreJ" class="form-control" value="{{$data['nbr']}}"></td>
<td><input type="text" name="prime" class="form-control" value="0"></td>
</tr>
#endforeach
#endif
</table>
</div>
</div>
<!-------------------//////////////////////////------------->
</div>
</body>
code ajax for checked all /uncheck and
<script type="text/javascript">
$(document).ready(function () {
$('#check_all').on('click', function(e) {
if($(this).is(':checked',true)) {
$(".checkbox").prop('checked', true);
} else {
$(".checkbox").prop('checked',false); } });
$('.checkbox').on('click',function(){
if($('.checkbox:checked').length == $('.checkbox').length){
$('#check_all').prop('checked',true);
}else{
$('#check_all').prop('checked',false); }});
$('.add-all').on('click', function(e) {
var idsArr = [];
$(".checkbox:checked").each(function() {
idsArr.push($(this).attr('data-id'));});
if(idsArr.length <=0) {
alert("Please select atleast one record to pointer.");
} else {
var strIds = idsArr.join(",");
$.ajax({
url: "{{ route('salarie.multiple-add') }}",
type: 'POST',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: {
'ids' : strIds},
success: function (data) {
if (data['status']==true) {
$(".checkbox:checked").each(function() {
alert(strIds); });
alert(data['message']);
} else {
alert('Whoops Something went wrong!!');}
window.location.reload()},
error: function (data) {
alert(data.responseText);}});} }); });
</script>
function controller addMultiple
public function addMultiple(Request $request){
$pointage=new Pointage();
$pointage->datep=$request->datep;
$pointage->nbrj=$request->nbrj;
$pointage->prime=$request->prime;
$pointage->solde=$request->solde;
return response()->json(['status'=>true]);
}

Apologies for late answer laptop died on me while i was busy but one way you could do it is by using array names for example:
<td><input type="checkbox" class="checkbox" name="row[$key][salarie]" data-id="{{$salarie->id}}"></td>
baiclly if you have multiple of these inputs with the same group it will make an array of inputs on your backend which you can loop through. to test this dd(request()); in your controller function above everything else. then you should be able to see what it returns in your console.
foreach(request(inputgroup) as $value){
Pointage::create([
'some_column' => $value['actualInputName']
]);
}
Update your function to something like this:
public function addMultiple(Request $request){
dd(request());
$pointage=new Pointage();
foreach(request('row') as $row){
// this is the important line $row is your request and ['salari'] is the name of the input
$pointage->salarie = $row['salarie'];
$pointage->save();
}
return response()->json(['status'=>true]);
}

Related

How to pass the date within an array to the database in laravel

I have made the following migration in Laravel:
public function up()
{
Schema::create('attendances', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('student_id');
$table->date('att_date')();
$table->string('status');
$table->timestamps();
});
}
My Form in Blade look like this
<form method="post" action="{{url('att-sumbit')}}" enctype="multipart/form-data">
#csrf
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4">
<strong>Date : </strong>
<input class="date form-control" type="text" id="datepicker" name="att_date[]">
</div>
</div>
<div class="mb-3">
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Level</th>
<th>Status</th>
</tr>
#foreach($students_att as $student)
<tr>
<td>{{$student -> id}}</td>
<td>{{$student -> name}}</td>
<td>{{$student -> level}}</td>
<td>
<input type="hidden" id="custId" name="student_id[]" value="{{$student -> id}}">
</td>
<td>
<select name="status[]">
<option value="0">No</option>
<option value="1">Yes</option>
</select>
</td>
</tr>
#endforeach
</table>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
<script type="text/javascript">
$('#datepicker').datepicker({
autoclose: true,
format: 'yyyy-mm-dd'
});
</script>
and I have made my Controller like this:
public function sumbit(Request $request)
{
/* $submit = new Attendance;
$submit->student_id = $request->get('student_id');
// $submit->att_date = $request->get('att_date');
// $submit->status = $request->get('status');
$submit->save();
return redirect('att'); */
$studentID = $request->input('student_id', []);
$studentDate = $request->input('att_date', []);
$studentStatus = $request->input('status', []);
$students = [];
foreach ($studentID as $index => $student) {
$students[] = [
"student_id" => $studentID[$index],
"att_date" => $studentDate[$index],
"status" => $studentStatus[$index],
];
}
$create = Attendance::insert($students);
}
so I want when i submit my form, it must be record the same date that i used by date picker to every input that show in the following image to my database
but when i did this procedure, i got this error (ErrorException
Undefined offset: 1) the error in this line in my controller line
"att_date" => $studentDate[$index],
How can Ii fix this error please help
"att_date" => $studentDate[$index], should be "att_date" => $studentDate[0]. You only have one date in that form.
Lets something more simple.
#foreach($students_att as $student)
<tr>
<td>{{$student -> id}}</td>
<td>{{$student -> name}}</td>
<td>{{$student -> level}}</td>
<td>
<input type="hidden" id="custId" name="student[student_id][]" value="{{ $student->id }}">
</td>
<td>
<select name="student[status][]">
<option value="0">No</option>
<option value="1">Yes</option>
</select>
</td>
</tr>
#endforeach
Controller :
$students = $request->student;
foreach($students as $key => $value) {
$students[$key]['att_date'] = $request->att_date[0];
}
$create = Attendance::insert($students);
Change the migration from date to timestamp, also use Carbon::parse before inserting it to the database.
Carbon::parse($datevariable)

Cart with login in laravel 5.7

I am implement shopping cart with login & witout login i am using cart package from laravel but it will stored cart item on local storage now i want to login and add cart item in database. When i am not login then item adds in local storage but when i am login then items add in database i am confuse. how i am implement I am sharing my code that i am developed need solutions
Controller:
public function add_to_cart(Request $req)
{
$userId=Session::get('userid');
$qty=$req->qty;
$product_id=$req->product_id;
$product_info=DB::table('product_details')
->join('subcategory','subcategory.sub_id','=','product_details.sub_id')
->select('subcategory.image','subcategory.name_of_subcategory','product_details.*')
->where('product_details.product_id',$product_id)->first();
$sub_id=$product_info->sub_id;
//dd($product_info);
Cart::add(array(
'id'=>$product_info->product_id,
'name'=>$product_info->name_of_subcategory,
'price'=>$product_info->price,
'qty'=>$qty,
'options'=>array('image' =>$product_info->image,'description'=>$product_info->description_of_product)
));
if($userId)
{
$content=\Cart::Content();
}
// $content=\Cart::Content();
// dd($content);
//$data = DB::select('select * from product_details where sub_id = ?',[$sub_id]);
//return view('productdetails',['data'=>$data]);
return view('cart');
}
blade
#extends('layout.header')
#section('content')
<?php
$contents=\Cart::Content();
?>
<div class="container mt-5">
<table id="cart" class="table table-hover table-condensed">
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>Quantity</th>
<th class="text-center">Subtotal</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach($contents as $v_contents)
<tr>
<td data-th="Product">
<div class="row">
<div class="col-sm-4 hidden-xs"><img src="{{asset('images/'.$v_contents->options->image)}}" alt="..." class="img-responsive"/ height="100" width="100"></div>
<div class="col-sm-8">
<h4 class="nomargin">{{$v_contents->name}}</h4>
<p>{{$v_contents->options->description}}</p>
</div>
</div>
</td>
<td data-th="Price">{{$v_contents->price}}</td>
<td data-th="Quantity">
<div class="plus-minus" style="width:150px; ">
<div class="input-group">
<span class="input-group-btn">
<button type="button" class="btn btn-default btn-number" id="subs" >
<span class="fa fa-minus"></span>
</button>
</span>
<input type="text" id="qty" name="qty" class="form-control input-number" value="{{$v_contents->qty}}" min="1" max="10">
<span class="input-group-btn">
<button type="button" class="btn btn-default btn-number" data-type="plus" id="adds">
<span class="fa fa-plus"></span>
</button>
</span>
</div>
<input type="hidden" name="product_id" id="product_id" value="{{ $v_contents->rowId}}">
</div>
</td>
<td data-th="Subtotal" class="text-center">{{ $v_contents->total}}</td>
<td class="actions" data-th="">
<a class="btn btn-danger btn-sm" href="{{ URL::to('/delete-to-cart/'.$v_contents->rowId)}}"><i class="fa fa-trash-o"></i></a>
</td>
</tr>
#endforeach
</tbody>
<tfoot>
<!-- <tr class="visible-xs">
<td class="text-center"><strong>Total 1.99</strong></td>
</tr> -->
<tr>
<td><i class="fa fa-angle-left"></i> Continue Shopping</td>
<td colspan="2" class="hidden-xs"></td>
<td class="hidden-xs text-center"><strong>Total {{\Cart::subtotal()}}</strong></td>
<td>Checkout <i class="fa fa-angle-right"></i></td>
</tr>
</tfoot>
</table>
</div>
<script type="text/javascript">
/*$('#adds').click(function add() {
var $qty = $("#qty");
var a = $qty.val();
a++;
$("#subs").prop("disabled", !a);
$qty.val(a);
});
$("#subs").prop("disabled", !$("#qty").val());
$('#subs').click(function subst() {
var $qty = $("#qty");
var b = $qty.val();
if (b >= 1) {
b--;
$qty.val(b);
}
else {
$("#subs").prop("disabled", true);
}
});*/
</script>
<script>
$(document).ready(function(){
$(document).on('click', '#adds', function(e) {
var qty = $('#qty').val();
var product_id=$('#product_id').val();
//alert(qty);
e.preventDefault()
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
jQuery.ajax({
url: "{{ url('/increment') }}",
method: 'get',
data: {
qty: qty,id:product_id
},
success: function(result){
jQuery('#qty').val(result.qty);
}});
});
});
</script>
<script>
$(document).ready(function(){
$(document).on('click', '#subs', function(e) {
var qty = $('#qty').val();
var product_id=$('#product_id').val();
//alert(qty);
e.preventDefault()
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
jQuery.ajax({
url: "{{ url('/decrement') }}",
method: 'get',
data: {
qty: qty,id:product_id
},
success: function(result){
jQuery('#qty').val(result.qty);
}});
});
});
</script>
#endsection

Vue js select box giving a couple of errors

I'm doing a site that uses laravel and vue js. The error I'm getting is this
[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "selected_parent"
and this
[Vue warn]: Error in v-on handler (Promise/async): "Error: Request failed with status code 404"
I can't see where I'm going wrong.
Here is my product.blade.php
#extends('layouts.public')
#section('content')
<div class="content_wrapper">
#foreach($single_product as $product)
<div class="row single_product_wrapper">
<div class="col-lg-8 col-md-12-col-sm-12 product_details">
#foreach($parent_product as $parent)
<h1>
{{ $parent->title }}
</h1>
<table style="width: 100%; height: 95px;" border="2" cellspacing="5" cellpadding="5">
<tbody>
<tr style="text-align: center;">
<td>
<strong>Code</strong>
</td>
<td>
<strong>Description</strong>
</td>
<td>
<strong>Price</strong>
</td>
</tr>
<tr style="text-align: center;">
<td>
{{ $parent->code }}
</td>
<td>
{{ $parent->description }}
</td>
<td>
{{ $parent->price }}
</td>
</tr>
</tbody>
</table>
#endforeach
<!-- BEGIN ADD TO CART FORM -->
<div id="app">
#foreach($parent_product as $parent)
<code-selection :products="{{ $parent_product }}" :children="{{ $parent->parent }}"></code-selection>
#endforeach
</div>
<!-- END ADD TO CART FORM -->
</div>
</div>
#endforeach
</div>
#stop
and this is my vue
<template>
<div>
<form #submit.prevent="submit">
<div class="row">
<div class="col-lg-12 code_select">
<select name="code" id="code" class="form-control mb-2 mt-10" v-model="selected_parent" required>
<option :value="selected_parent">Please select your code</option>
<option v-for="product in products" :value="product.id">
{{ product.code }}
</option>
<option v-for="child in children" :value="child.id">
{{ child.code }}
</option>
</select>
</div>
</div>
<input type="submit" class="btn btn-dark btn-lg btn-block" value="Add To Cart">
</form>
</div>
</template>
<script>
import axios from 'axios'
export default {
props: [
'products',
'children',
'selected_parent'
],
mounted() {
console.log('Component mounted.')
},
methods: {
submit(){
var formData = new FormData();
formData.append('code', this.selected_parent);
return axios.post('/add-to-cart/'+this.selected_parent, formData)
.then(
function(response)
{
console.log(response.data.redirect);
window.location = response.data.redirect;
}
);
},
},
}
</script>
So what I would like to happen is, when the user selects a code and hits the Add To Cart button they will then get taken to the cart page, but right now
that isn't happening when I select the code and hit the button nothing happens and I get the errors that I said in my console.
If there is anything else you need to know please let me know
The answer is simple, you should break the direct prop mutation by assigning the value to some local component variables(could be data property, computed with getters, setters, or watchers).
Here's a simple solution using the watcher.
<template>
<input
v-model="input"
#input="updateInput" />
</template>
<script>
export default {
props: {
value: {
type: String,
default: '',
},
},
data() {
return {
input: '',
};
},
watch: {
value: {
handler(after) {
this.input = after;
},
immediate: true,
},
},
methods: {
updateInput() {
this.$emit('input', this.input);
},
},
};
</script>
It's what I use to create any data input components and it works just fine. Any new variables sent by parent v-model will be watched and assigned to the input variable and once the input is received, catch that action and emit input to parent suggesting that data is input from the form element.
And for the second part, when you receive the new url from redirect, simply replace the location href like this:
return axios.post('/add-to-cart/'+this.selected_parent, formData)
.then((response) => {
window.location.href = response.data.redirect;
})
.catch((error) => {
console.log(error);
})
);

Why ajax calling for search doesn't display output?

I had search field using ajax call in laravel 5. It search in Db and display output in table. When user click on the page, it should display all db query. When user type in search field it should display the output according to the search input.
This is the controller for searching:
function action(Request $request)
{
if($request->ajax())
{
$output = '';
$query = $request->get('query');
if($query != '')
{
$data = DB::table('itemregistrations')
->where('name', 'like', '%'.$query.'%')
->paginate(10);
}
else
{
$data = DB::table('itemregistrations')
->paginate(10);
}
$total_row = $data->count();
if($total_row > 0)
{
foreach($data as $row)
{
$output .= '
<tr>
<td>'.$row->name.'</td>
<td>'.$row->seksyen_kecil.'</td>
<td>'.$row->nobadan.'</td>
</tr>
';
}
}
else
{
$output = '
<tr>
<td align="center" colspan="5">No Data Found</td>
</tr>
';
}
$data = array(
'table_data' => $output,
'total_data' => $total_row
);
echo json_encode($data);
}
}
This is the view blade displaying the output:
<div class="row">
<div class="form-group">
<div class="col-lg-5">
<input type="text" class="form-control" id="search" name="search"></input>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">Senarai Kakitangan</div>
<div class="panel-body">
#if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
#endif
#if(Auth::check())
<div class="container table-responsive col-lg-12">
<!-- <div class="container text-center"> -->
<h3 align="center">Total Data : <span id="total_records"></span></h3>
<table class="table table-striped table-bordered">
<thead>
<tr>
<td><strong>#</strong></td>
<td class="text-center col-lg-1"><strong>Nama</strong></td>
<td class="text-center col-lg-3"><strong>Seksyen</strong></td>
<td class="text-center col-lg3-2"><strong>No Badan</strong></td>
</tr>
</thead>
<tbody>
</tbody>
</table>
<!-- </div> -->
<ul class="pagination pull-right">
{{ $itemregistrations->links() }}
</ul>
</div>
#endif
#if(Auth::guest())
Anda perlu log masuk.
#endif
</div>
</div>
</div>
The javascript for searching:
<script>
$(document).ready(function(){
fetch_profil_data();
function fetch_profil_data(query = '')
{
$.ajax({
url:"{{ route('live_search.action') }}",
method:'GET',
data:{query:query},
dataType:'json',
success:function(data)
{
$('tbody').html(data.table_data);
$('#total_records').text(data.total_data);
}
})
}
$(document).on('keyup', '#search', function(){
var query = $(this).val();
fetch_profil_data(query);
});
});
</script>
The route for the search is:
Route::get('/profil/action', 'Modul\ProfilController#action')->name('live_search.action');
I couldn't find any error and console.log also doesn't produce any output..
The searching doesn't work and don't display any result.
The script link i put in app.blade.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
This is the error in log
C:\\xampp\\htdocs\\hre1m\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php(116): Illuminate\\Foundation\\Http\\Kernel->sendRequestThroughRouter(Object(Illuminate\\Http\\Request))
#50 C:\\xampp\\htdocs\\hre1m\\public\\index.php(53):
Illuminate\\Foundation\\Http\\Kernel->handle(Object(Illuminate\\Http\\Request))
#51 C:\\xampp\\htdocs\\hre1m\\server.php(21):
require_once('C:\\\\xampp\\\\htdocs...')
#52 {main}
"}

Laravel Route for Search

I try this tutorial on laravel about Live Search
But it's on the homepage(index)
I want to access it to localhost/laravel/public/search
Here is the Controller
class SearchController extends Controller
{
public function index()
{
return view('search.search');
}
public function search(Request $request)
{
if ($request->ajax())
$output ="";
$orderinfo=DB::table('tb_order')->where('shipcustomername','LIKE','%' . $request->search.'%' )
->orWhere('orderId','LIKE','%' .$request->search. '%')->get();
if ($orderinfo)
{
foreach ($orderinfo as $key =>$orderinfo ){
$output.='<tr>' .
'<td>' .$orderinfo->orderId .'</td>' .
'<td>' .$orderinfo->email .'</td>' .
'<td>' .$orderinfo->subsource .'</td>' .
'</tr>';
}
return Response($output);
}
and my route
Route::get('/' ,'SearchController#index');
Route::get('/search' ,'SearchController#search');
on my resources folder
i have folder search and it's contain the search.blade.php
<div class="container">
<div class="row">
<div class="panel panel-default">
<div class="panel-heading">
<h3>Order Info</h3>
</div>
<div class="panel-body">
<div class="form-group">
<input type="text" class="form-control" id="search" name="search"></input>
</div>
<table class="table table-bordered table-hover ">
<thead>
<tr>
<th>OrderID</th>
<th>Email</th>
<th>SubSource</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
<script type="text/javascript">
$('#search').on('keyup',function(){
$value=$(this).val();
$.ajax({
type : 'get',
url : '{{URL::to('search')}}',
data : {'search':$value},
success:function(data){
$('tbody').html(data);
}
});
});
</script>
</body>
I know this is the route for index ,
Route::get('/' ,'SearchController#index');
But if try to change this to
Route::get('search' ,'SearchController#index');
I get error 500
What is the correct way to route this so it will not use the index
Thank you
There is a good chance that you are sending empty data try to change this:
$value=$(this).val();
to this:
var value = $('#search').val();
If no that then also you are not submitting the data as well add the form:
{{ Form::open(array('method'=>'GET','class'=> 'col-md-6','url' => '/search', 'id'=>'searchform')) }}
<div class="form-group">
<input type="text" class="form-control" id="search" name="search"></input>
</div>
{{ Form::close() }}
change your ajax request to this:
$('#searchform').on('submit', function(e) {
e.preventDefault();
var search = $('#search').val();
$.ajax({
type: "GET",
url: {{URL::to('search')}},
data: {search:search}
success:function(data){
$('tbody').html(data);
}
});
});
If not that then:
set APP_DEBUG in .env to true since the request is ajax, using chrome and press f12, go to Network tab -> click on error -> preview tab, if it just say error with a blank screen, then maybe you should chmod 775(write permissions) and try again

Resources