laravel delete is not working - ajax

I am wondering how to put a csrf token in a form so that delete will work?
Here is my code:
Route:
Route::delete('category_delete/{id}',['as'=>'category_delete','uses'=>'CategoryController#destroy']);
index.blade.php
#section('adminContent')
{!! Form::token() !!}
<div class="table-responsive art-content">
<table class="table table-hover table-striped">
<thead>
<th> NAME</th>
<th> ACTIONS</th>
</thead>
<tbody>
#foreach($categoriesView as $category)
<tr>
<td>{!! $category->name!!}</td>
<td>{!! link_to_route('categories.edit', '', array($category->id),array('class' => 'fa fa-pencil fa-fw')) !!}</td>
<td><button type="button" id="delete-button" class="delete-button" data-url = "{!! url('category_delete')."/".$category->id !!}"><i class="fa fa-trash-o"></i></button>
</td>
</tr>
#endforeach
</tbody>
</table>
<div class="pagination"> {!! $categoriesView->render() !!}</div>
</div>
#stop
CategoryController:
public function destroy($id,Category $category)
{
$category = $category->find ( $id );
$category->delete ();
Session::flash ( 'message', 'The category was successfully deleted!.' );
Session::flash ( 'flash_type', 'alert-success' );
}
If I used ajax, javascript or jquery, how should the code be?

Using jquery I would do something like the following.
Add the line below in the header of your home view
<meta name="csrf-token" content="{{ csrf_token() }}" />
Now in your javascript
function deleteMe(button)
{
// You might want to put the ajaxSetup function where it will always load globally.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
if(confirm("Are you sure?"))
{
$.get(
'category_delete/'+button.id,
function( response )
{
// callback is called when the delete is done.
console.log('message = '+ response.message);
}
)
}
}
In index.blade.php, make your id more specific.
...
<td><button type="button" id=".$category->id" class="delete-button" data-url = "{!! url('category_delete')."/".$category->id !!}"><i class="fa fa-trash-o" onlick="deleteMe(this);></i></button>
...
In your controller
public function destroy($id,Category $category){
$category = $category->find ( $id );
$category->delete ();
return response()->json(
'message' => 'Deleted',
)
}
Note: No need to add
Form::token in your view
Hope this helps.....
Updated...........
If you were to do it using laravel only, I will suggest you use a link rather than the button you are using.
In index.blade.php, make your id more specific.
...
<td><a href="category_delete/".$category->id class="delete-button" data-url = "{!! url('category_delete')!!}"><i class="fa fa-trash-o"></i></td>
...
In your controller
public function destroy($id,Category $category){
$category = $category->find ( $id );
$category->delete ();
return view('index');//important.
}
If you want your link to look like a button, use css or a css framework like bootstrap
That should be it. hope this helps again.

Related

Using v-for in laravel + vue.js, am trying to display a table containing information of the user but nothing shows

<script>
export default {
name: "OutPatient",
data(){
return{
out_patients: {}
}
},
methods: {
index(){
axios.get('/data/out_patient').then(({data}) =>
(this.out_patients = data.data));
},
update(){}
},
created(){
this.index();
}
}
</script>
<tr v-for="out_patient in out_patients" v-bind:key="out_patient.id">
<td>{{out_patient.id}}</td>
<td>{{out_patient.first_name}}</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
<i class="fa fa-edit blue"></i>
|
<i class="fa fa-trash red"></i>
</td>
</tr>
This is my code but the data is not showing in the table even though in the XHR the data shows there.
In the inspect element I can see the data but the v-for loop is unable to display the data.
Seems to me like you tried to extract data twice, you have this:
axios.get('/data/out_patient').then(({data}) =>
(this.out_patients = data.data));
if you already extract it here: {data} then you don't need data.data, only data below?
index() {
this.error = this.out_patients = null;
this.loading = true;
axios
.get('/data/out_patient')
.then(response => {
this.loading = false;
this.out_patients = response.data;
}).catch(error => {
this.loading = false;
this.error = error.response.data.message || error.message;
});
},
this rather works for me.
thank you all for the support
can you try fetching the data on mounted life cycle hook instead of created in order to populate the table with data on page load mounted is the best hook lifecycle as much I know.
<script>
export default {
name: "OutPatient",
data(){
return{
out_patients: {},
out_patient:'',
}
},
methods: {
index(){
axios.get('/data/out_patient')
.then(({data}) =>
(this.out_patients = data.data));
},
update(){
}
},
created(){
this.index();
}
}
</script>
<tr v-for="out_patient in out_patients" v-bind:key="out_patient.id">
<td>{{out_patient.id}}</td>
<td>{{out_patient.first_name}}</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
<a href="#">
<i class="fa fa-edit blue"></i>
</a>
|
<a href="#">
<i class="fa fa-trash red"></i>
</a>
</td>
</tr>
Just declare out_patient in data. I hope this solves your issue.
And also check if out_patients is returning data.

How to showing data on table with datatables 'yajra'

I following this tutorial : How to route in Laravel DataTables
its so simple , but i cant do it . after i set my controller and my route and view , its not showing data and and table. in the table i have a button like'action' how i can take this comand to this button ?
can you check my faulth query
Route::get('user/show1', 'userController#show')->name('usershow1');
Route::get('user/show1-dt', 'userController#indexDataTables')->name('usershow1dt');
controller
public function show()
{
$pemeliharaan = Pemeliharaan::with(['user','alat'])->where('status','harian')->get();
return view('users.view_harian',['pemeliharaan' => $pemeliharaan]);
}
public function indexDataTables()
{
$pemeliharaan = Pemeliharaan::query();
// return DataTables::eloquent($pemeliharaan)->toJson();
return Datatables::of($pemeliharaan)->make(true);
}
and i have a view like this . the page number,search and pagination is showing at view ,but this data not showing. can you correctted this view ?
<div class="box-body table-responsive no-padding">
<table class="table table-hover" id="table">
<tbody><tr>
<th>No</th>
<th>Nama Alat</th>
<th>status</th>
<th>User Input</th>
<th>Action</th>
<th>Tanggal</th>
</tr>
{{-- #php ---> before i suing datatables my view like that
$no=0;
#endphp
#foreach ($pemeliharaan as $i)
<tr>
<td>{{ ++$no }} </td>
<td>{{ $i->alat->nama_alat}}</td>
<td>{{ $i->status}}</td>
<td>{{ $i->user->name}}</td>
<td> Lihat Data</span> </td>
<td>{{ $i->created_at}}</td>
</tr>
#endforeach --}}
</tbody></table>
</div>
.
.
#endsection
#push('scripts')
<script>
$(function() {
$('#table').DataTable({
processing: true,
serverSide: true,
ajax: '{!! route('usershow1dt') !!}',
columns: [
{ data: 'nama_alat', name: 'nama_alat'},
{ data: 'status', name: 'status'},
{ data: 'User Input', name: 'nama'},
{ data: 'Action', name: 'name'},//here my button
{ data: 'Tanggal', name: 'created_at'},
],
});
})
</script>
#endpush
Try This:
public function show() {
$pemeliharaan = Pemeliharaan::where('user','alat')->where('status','harian')->get();
return view('users.view_harian',['pemeliharaan' => $pemeliharaan]);
}

Real Live Search and Filter Laravel

I'm new on Laravel and try to implement real live search and filter on my project, but it doesn't work at all. I dont understand ajax ver much and just copy paste the code from other website. I tried to understand the code and I think its correct but it doesn't work, so please help. Thanks
Here is my controller
public function search(Request $request)
{
if($request->ajax())
{
$output = '';
$query = $request->get('query');
if($query != '')
{
$data = Service::table('service')
->where('keterangan', 'like', '%'.$query.'%')
->orWhere('biaya', 'like', '%'.$query.'%')
->get();
}
else
{
$data = Service::table('service')
->orderBy('kodeService', 'asc')
->get();
}
$total_row = $data->count();
if($total_row > 0)
{
foreach($data as $row)
{
$output .= '
<tr>
<td>'.$row->kodeService.'</td>
<td>'.$row->keterangan.'</td>
<td>'.$row->biayaService.'</td>
</tr>
';
}
}
else
{
$output = '
<tr>
<td align="center" colspan="5">No Data Found</td>
</tr>
';
}
$data = array(
'table_data' => $output
);
echo json_encode($data);
}
}
This is the script
$(document).ready(function(){
fetch_customer_data();
function fetch_customer_data(query = '')
{
$.ajax({
url:"{{ route('live_search.action') }}",
method:'GET',
data:{query:query},
dataType:'json',
success:function(data)
{
$('#table tbody').html(data.table_data);
}
});
}
$(document).on('keyup', '#search', function(){
var query = $(this).val();
fetch_customer_data(query)
});
});
Route :
Route::resource('service', 'ServiceController');
Route::get('service/search', 'Service#search')->name('live_search.action');
And index.blade
<table class="table table-striped table-hover table-bordered" id="table">
<thead>
<tr>
<th>Kode Service</th>
<th>Keterangan</th>
<th>Biaya</th>
<th>Aksi</th>
</tr>
</thead>
<tbody>
#foreach($service as $data)
<tr>
<td><?= $data->kodeService?></td>
<td><?= $data->keterangan ?></td>
<td><?= $data->biayaService?></td>
<td>
<a class="btn btn-sm btn-info" href="{{ route('service.edit', $data['kodeService']) }}"> <i class="oi oi-pencil"></i> Edit</a>
<button type="button" class="btn btn-sm btn-danger" data-toggle="modal" data-target="#myModal"><span class="oi oi-trash"></span> Hapus</button>
</td>
</tr>
#endforeach
</tbody>
</table>
Put your route like this :
Route::get('service/search', 'ServiceController#search')->name('live_search.action');
Route::resource('service', 'ServiceController');
After that open the Browser Console panel (Press F12 to open it) and check the Ajax request in Network tab.
Where you can get the specific error if any in the Response tab.
If you need an extra route to your resource route,you should place the new route before the resource route.
Route::get('service/search', 'ServiceController#search')->name('live_search.action');
Route::resource('service', 'ServiceController');

How to display subnested arrays in Vue search component - Laravel

I'm having issues displaying eloquent relationship data via my vue.js search template, specifically my customer->biller fields.
models.student_first_name will display however
models.billers.biller_first_name wont show anything
The search function is working on my customers.index view using the following
CustomerDetailsController:
public function getData(Request $request){
$search = $request->search;
$customer = Customer::with('orders', 'billers', 'paymentplans', 'paidinfulls')->where(DB::raw('concat(student_first_name," ",student_last_name)'), 'like', '%'.$search.'%')->paginate(20);
return response()->json([
'model' => $customer
]);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$customers = Customer::with('orders', 'paymentplans', 'billers')->orderBy('created_at', 'desc')->where('owner', Auth::user()->name)->paginate(25);
return view('customers.index', compact('customers', 'orders', 'paymentplans', 'funding'));
}
Customers.vue:
<template>
<div class="container">
<div class="field m-b-20">
<p class="control has-icons-left">
<input #keyup="fetchDataCustomer()" type="text" class="form-control input" name="search" v-model="search" placeholder="Search">
<span class="icon is-small is-left"><i class="fa fa-search"></i></span>
</p>
</div>
<table class="table">
<thead>
<tr>
<th>Student Name</th>
<th>Email</th>
<th>Biller Name</th>
<th>Biller Email</th>
<th>Courses Purchased</th>
<th>Deposit</th>
<th>Payment Plan</th>
<th>Accepted</th>
<th>Receipted</th>
</tr>
</thead>
<tbody>
<tr v-for="models in model.data">
<td>{{models.student_first_name}} {{models.student_last_name}}</td>
<td>{{models.student_email}}</td>
<td>{{models.billers.biller_first_name}}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import axios from 'axios'
export default{
data(){
return {
model: {},
search:'',
url:'api/customers'
}
},
created:function (){
this.fetchDataCustomer()
},
methods: {
fetchDataCustomer(){
var vm = this
axios.get(`${this.url}?search=${this.search}`)
.then(function (response) {
Vue.set(vm.$data, 'model', response.data.model)
})
}
}
}
</script>
JSON output of a search result
{"model":{"current_page":1,"data":[{"id":"627d0130-4dd0-11e8-91dd-69869f509337","enrolment_id":"John","student_first_name":"John","student_last_name":"Smith","student_email":"johnsmith#mail.com","address":"123 Test Street","suburb":"Townsville","postcode":"9999","state":"AAA","home_phone":null,"work_phone":null,"mobile_phone":"0444444444","dob":"1999-01-01 00:00:00","drivers_license_number":"123738974987498","owner":"Sales Man","owner_email":"salesman#business.com","created_at":"2018-05-02 16:16:43","updated_at":"2018-05-02 16:16:43","orders":[{"id":933,"fc_account":16,"customer_id":"627d0130-4dd0-11e8-91dd-69869f509337","biller_id":246,"enrolment_id":"John","course_id":5,"delivery_mode":0,"course_cost":"2000.00","deposit":null,"gov_funding":"0","location":"0","Monday":0,"Tuesday":0,"Wednesday":0,"Thursday":0,"Friday":0,"Saturday":0,"Sunday":0,"start_time":null,"end_time":null,"start_date":null,"enrolment_issue_date":"2018-05-02","sale_type":2,"created_at":"2018-05-02 16:17:24","updated_at":"2018-05-02 16:17:24"}],"billers":[{"id":246,"customer_id":"627d0130-4dd0-11e8-91dd-69869f509337","biller_first_name":"John","biller_last_name":"Smith","biller_email":"johnsmith#mail.com","biller_address":null,"biller_suburb":null,"biller_postcode":null,"biller_state":null,"biller_phone":null,"created_at":"2018-05-02 16:17:24","updated_at":"2018-05-02 16:17:24"}],"paymentplans":[{"id":"836e7e40-4dd0-11e8-a907-83f96c25a7d0","enrolment_id":"John","customer_id":"627d0130-4dd0-11e8-91dd-69869f509337","paysmart_id":"FIT69869f509337","biller_id":246,"biller_first_name":"John","biller_last_name":"Smith","biller_email":"johnsmith#mail.com","payment_method":-1,"contract_value":"1500.00","interest_free":1,"payment_frequency":1,"commencement_date":"2018-05-24 00:00:00","payment":"100.00","first_payment":"200.00","admin_fee":"1.30","setup_fee":"5.50","deposit":"500.00","deposit_payment_method":"Cash","special_conditions":null,"accepted":null,"accepted_student":null,"created_at":"2018-05-02 16:17:38","updated_at":"2018-05-02 16:17:38","submitted":1,"biller_ip":null,"student_ip":null}],"paidinfulls":[]}]
Vue Debug
Your models.billers is an array but you're treating it as an object. So you'll have to access it via models.billers[0].biller_first_name instead of models.billers.biller_first_name given that it is always available.

Ajax call not working on datatables pages,except first page

i am using datatables.And on the table there is button on each row.
When I click on the trash button,ajax works only for the first 10 row.
But when I move on to next pages it does not work anymore.
Here is my table code:
<script type="text/javascript" language="javascript" src="//cdn.datatables.net/plug-ins/725b2a2115b/integration/bootstrap/3/dataTables.bootstrap.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#example').dataTable();
} );
</script>
<table id="example" class="table table-bordered">
<thead>
<tr>
<th class="success">Id</th>
<th class="success">Image</th>
<th class="success">Title</th>
<th class="success">Action</th>
</tr>
</thead>
<tbody>
<?php
$query = mysqli_query($connect,"SELECT * FROM movie");
while ($result = mysqli_fetch_row($query)){
echo'
<tr>
<td>'.$result[0].'</td>
<td><img class="img-responsive" style="max-height:50px;" src="'.$result[5].'"></td>
<td>'.$result[1].'</td>
<td>
<div class="btn-group" data-toggle="buttons">
<label id="remID" class="btn btn-sm btn-default">
<span class="text-danger glyphicon glyphicon-trash"></span>
</label>
<label class="btn btn-sm btn-default">
<span class="text-primary glyphicon glyphicon-edit"></span>
</label>
</div>
</td>
</tr>
';
echo'
<script>
$(document).ready(function(){
$("#remID").click(function(){
$.post("remMovie.php",
{
id:"'.$result[0].'"
},
function(data,status){
alert(status);
});
});
});
</script>
';
}
?>
</tbody>
</table>
Here is my PHP part of ajax action:
<?php
include('adminchk.php');
include('config.php');
$movieID = $_POST['id'];
$query = mysqli_query($connect,"DELETE from movie where id='$movieID'");
if ($query){
echo"movie deleted";
}
else {
echo"ERROR!";
}
?>
I dont know why this is happening.I want the trash button to work for every row of datatable.
To execute any Code after the Data Table has been paginated (basically redrawn), you need to add fnDrawCallback function inside .dataTabale() method. All codes written inside the Callback function will work after the table has been redrawn. Here is an example...
$(document).ready( function() {
$('#example').dataTable({
"fnDrawCallback": function( oSettings ) {
// Write any code (also ajax code that you want to execute)
// that you want to be executed after
// the table has been redrawn
}
});
});
You should try something like fnDrawCallback event.
Here is the doc : http://legacy.datatables.net/usage/callbacks#fnDrawCallback
When the datable change, you bind the buttons with the function you want.
JS :
$(document).ready( function() {
$('#example').dataTable( {
"fnDrawCallback": function( oSettings ) {
alert( 'DataTables has redrawn the table' );
}
} );
} );

Resources