Laravel 8 Delete Data Using Bootstrap Model - javascript

I have a table made with Bootstrap and I want to delete the data with bootstrap model confirm. Deleting works fine without model, but with model, delete button always send last row data to the model no matter which row delete button clicked.
model button
<i class="fe fe-trash text-danger fe-24"></i>
Modal delete button
<form action="{{ route('admin.users.delete', $user) }}" method="post">
#csrf
<button type="submit" class="btn mb-2 btn-danger">Delete</button>
</form>
js used
$('#deleteModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget)
var recipient = button.data('user')
});
table foreach
<tbody>
#if ($users->count())
#foreach ($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>(478) 446-9234</td>
<td>159 address</td>
<td>
#if ($user->user_role == 0)
User
#elseif ($user->user_role == 1)
Editor
#else Admin
#endif
</td>
<td>{{ $user->created_at->format('M d, Y') }}</td>
<td>{{ $plans->find($user->plan_id)->name }}</td>
<td>
#if ($user->expiration_date != null)
{{ Carbon\Carbon::parse($user->expiration_date)->format('M d, Y') }}
#else
N/A
#endif
</td>
<td>
#if ($user->is_active == 1)
<span class="text-success font-weight-bold">Active</span>
#else
<span class="text-danger font-weight-bold">Disabled</span>
#endif
</td>
<td>
<i class="fe fe-edit text-secondary fe-24"></i>
<i class="fe fe-trash text-danger fe-24"></i>
</td>
</tr>
#endforeach
#endif
</tbody>

I am assuming that you have a foreach to creat the delete button s for every user
The $user that is passed will always be the last $user id
You need to pass the $user that was clicked
and pass this the the action of the form
try
var deleteModal = $('#deleteModal');
$('a').on('click', function (e) { // this is the "a" tag
var userId = $(this).data('user'),
var submitUrl = {!! url("/admin/users/delete/") !!}+userId;
var form = $('#form');
form.attr('action', submitUrl);
});
});
when the is clicked ,store the data-user and create the submit and change the form action
Hope this would be of any help to you.

Related

Export pdf with javascript in laravel

my code in index.blade.php to display the data to be exported to pdf.
<div class="card-body">
<div class="table-responsive table-bordered" id="pdf">
<table class="table mb-0">
<thead>
<tr>
<th>NAMA</th>
<th>PERUSAHAAN</th>
<th>LOKASI ABSEN</th>
<th>MASUK</th>
<th>PULANG</th>
<TH>KETERANGAN</TH>
</tr>
</thead>
<tbody>
#foreach ($absen as $data)
#php
$work_hour_start = $data->work_hour_start;
$attendance_time = \Carbon\Carbon::parse($data->in_time)->format('H:i:s');
$tolerance = \Carbon\Carbon::parse($attendance_time)->subMinutes($data->late_tolerance);
$hour = $tolerance->format('H:i:s');
$attendance_grp = \App\Models\AttendanceGroup::where('id', $data->attendance_group_id)
->select('ignore_work_hour')
->first();
if (isset($attendande_grp)) {
if ($data->ignore_work_hour == 0 || $attendance_grp->ignore_work_hour == 0) {
if ($hour > $work_hour_start) {
$is_late = 'Terlambat';
} else {
$is_late = 'Tepat Waktu';
}
}
}
#endphp
<tr>
<td>{{ $data->name ?? '' }}</td>
<td>{{ $data->alias ?? '' }}</td>
<td>{{ $data->location_name ?? '' }}</td>
<td>
<span class="badge badge-success">
{{ Carbon\Carbon::parse($data->in_time)->format('H:i:s') }}
</span>
</td>
<td>
<span class=" #if ($data->out_time != null) badge badge-info #else #endif">
#if ($data->out_time != null)
{{ Carbon\Carbon::parse($data->out_time)->format('H:i:s') }}
#else
{{ '-' }}
#endif
</span>
</td>
<td>{{ $is_late }}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
result view
my javascript code to export pdf data from index.blade.php
<script>
var doc = new jsPDF();
function printDiv(divId,title)
{
let mywindow = window.open('', 'PRINT', 'height=650,width=900,top=100,left=150');
mywindow.document.write(`<html><head><title>${title}</title>`);
mywindow.document.write('</head><body >');
mywindow.document.write(document.getElementById(divId).innerHTML);
mywindow.document.write('</body></html>');
mywindow.document.close(); // necessary for IE >= 10
mywindow.focus(); // necessary for IE >= 10*/
mywindow.print();
mywindow.close();
return true;
}
</script>
results after exporting pdf
in my view i create data in tableform, i will export this data in tableform too, but the problem is the view after i export is not in table form, to export pdf i use javascript, is there any way to change my javascript code to export pdf so it can take the form of a table?
it is simple . because when you are creating the html to print with javascript . you simply DO NOT include the files related to styles . if there is a css file for styling you should include that in the html you are creating with js . or else if there is a bootstrap link to style elements include the link to cdn in the tag
your javascript would be something like that :
mywindow.document.write(`<html><head><title>${title}</title>`);
mywindow.document.write('<link rel="stylesheet" type="text/css" href="your css path">');
mywindow.document.write('</head><body >');
the rest of code...

Laravel destroy nested resource

I have a resource name OrganizationEmailDomain
Route::resource('organizations.emaildomains', 'OrganizationEmailDomainController', ['except' => ['show']]);
and able to index it just fine
In that view, when clicking in the three dots there's the destroy part
<form action="{{ route('organizations.emaildomains.destroy', ['organization' => $id, 'emaildomain' => $email_domain->id]) }}" method="post">
#csrf
#method('delete')
<button type="button" class="dropdown-item" onclick="confirm('{{ __("Are you sure you want to delete this email domain?") }}') ? this.parentElement.submit() : ''">
{{ __('Delete') }}
</button>
</form>
If in that index view I echo $email_domains (<?php echo $email_domains;?>) then I get as expected (note that the following was before the images were added, so the records don't match the images)
[{"id":1,"email_domain":"test.com","organization_id":1,"created_at":"2021-03-02T14:46:50.000000Z","updated_at":"2021-03-02T14:46:56.000000Z"},{"id":2,"email_domain":"gmail.com","organization_id":1,"created_at":null,"updated_at":null}]
When I try to destroy
/**
* Remove the specified resource from storage.
*
* #param \App\OrganizationEmailDomain $emailDomain
* #return \Illuminate\Http\Response
*/
public function destroy(Organization $organization, OrganizationEmailDomain $emailDomain)
{
//dd($emailDomain);
$emailDomain->delete();
return redirect()->route('organizations.emaildomains.index',$organization->id)->withStatus(__("Organization's email domain successfully deleted."));
}
that dd($emailDomain) returns this
As langbox states
(...) hasMany relationship (...) so it returns a Collection always
So, inspired in this answer from Dan, just substituted
$emailDomain->delete();
with the following
$org_email = OrganizationEmailDomain::where('id', $organization->org_email_domains->pluck('id'))->delete();
given that in Organization model I have
/**
* Get the email domains of the organization
*
* #return void
*/
public function org_email_domains()
{
return $this->hasMany(OrganizationEmailDomain::class);
}
What's the problem here?
It always deletes the record that is in the row above.
For example, let's delete DDDDDDDDDDDDDDDDDDD
this deleted the first row, AAAAAAAAAAAAAAAAA
If I then try to delete BBBBBBBBBBBBBBB (which now became the first row) it'll delete just fine.
For reference, here's the index.blade.php where the form I shared previously is at
<table class="table table-flush" id="datatable-basic">
<thead class="thead-light">
<tr>
<th scope="col">{{ __('Organization') }}</th>
<th scope="col">{{ __('Email Domain') }}</th>
<th scope="col">{{ __('Creation date') }}</th>
#can('manage-org-emaildomains', App\User::class)
<th scope="col"></th>
#endcan
</tr>
</thead>
<tbody>
#foreach ($email_domains as $email_domain)
<tr>
<td>{{ $organization->name }}</td>
<td>{{ $email_domain->email_domain }}</td>
<td>{{ $email_domain->created_at ? $email_domain->created_at->format('d/m/Y H:i') : "NULL" }}</td>
#can('manage-org-emaildomains', App\User::class)
<td class="text-right">
#if (auth()->user()->can('update', $email_domain) || auth()->user()->can('show', $email_domain) || auth()->user()->can('delete', $email_domain))
<div class="dropdown">
<a class="btn btn-sm btn-icon-only text-light" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="fas fa-ellipsis-v"></i>
</a>
<div class="dropdown-menu dropdown-menu-right dropdown-menu-arrow">
#can('show', $email_domain)
<a class="dropdown-item" href="{{ route('organizations.emaildomains.show', ['organization' => $id, 'emaildomain' => $email_domain->id]) }}">{{ __('Show') }}</a>
#endcan
#can('update', $email_domain)
<a class="dropdown-item" href="{{ route('organizations.emaildomains.edit', ['organization' => $id, 'emaildomain' => $email_domain->id]) }}">{{ __('Edit') }}</a>
#endcan
#if (auth()->user()->can('delete', $email_domain))
<form action="{{ route('organizations.emaildomains.destroy', ['organization' => $id, 'emaildomain' => $email_domain->id]) }}" method="post">
#csrf
#method('delete')
<button type="button" class="dropdown-item" onclick="confirm('{{ __("Are you sure you want to delete this email domain?") }}') ? this.parentElement.submit() : ''">
{{ __('Delete') }}
</button>
</form>
#endif
</div>
</div>
#endif
</td>
#endcan
</tr>
#endforeach
</tbody>
</table>
You cant delete just the id, you are passing only the id.
in the controller you Must do Find , Ex :
$flight = Flight::find($emaidomain);
then u do
$flight->delete();
You are just passing id in the form, you must find the item in the controller via the id then delete, u cant delete id only.
I've changed the route to shallow nesting
Route::resource('organizations.emaildomains', 'OrganizationEmailDomainController', ['except' => ['show']])->shallow();
then the form to
<form action="{{ route('emaildomains.destroy', ['organization' => $id, 'emaildomain' => $email_domain->id]) }}" method="post">
#csrf
#method('delete')
<button type="button" class="dropdown-item" onclick="confirm('{{ __("Are you sure you want to delete this email domain?") }}') ? this.parentElement.submit() : ''">
{{ __('Delete') }}
</button>
</form>
and the destroy() to
/**
* Remove the specified resource from storage.
*
* #param \App\OrganizationEmailDomain $emailDomain
* #return \Illuminate\Http\Response
*/
public function destroy(Request $request, OrganizationEmailDomain $emailDomain)
{
$path = $request->path();
$id = substr($path, strrpos($path, '/') + 1);
$emailDomain = OrganizationEmailDomain::find($id);
$emailDomain->delete();
return redirect()->route('organizations.emaildomains.index',$request->query()['organization'])->withStatus(__("Organization's email domain successfully deleted."));
}
and now it works fine.

Auto check child when parent is checked in javascript + php laravel

i had a problem which is when parent is ticked , then the child is automatically checked .
Image
my code
<tbody id="catRecord">
#php $catCode = ""; #endphp
#if(!empty($data))
#foreach($data as $i=>$cat)
#if($cat->cc_category_code != $catCode )
#if(isset($cat->irel__ref_category))
<tr class="c_row">
<td style='width: 300px;'>
#for($j=0; $j<$cat->irel__ref_category->Ct_Level; $j++)
#endfor
- {{ $cat->irel__ref_category->Ct_Abbreviation }} // parent data
</td>
<td style='width: 600px;'>{{ $cat->irel__ref_category->Ct_Description }}</td> //child data
<td style='width: 20px;'><input type="checkbox" class="ss" name="ss[]" id="ss[]" value="{{ $cat->irel__ref_category->Ct_Code }}^{{ $cat->irel__ref_category->Ct_Abbreviation }}^{{ $cat->irel__ref_category->Ct_Description }}" />
</td>
<input type="hidden" id="cat[]" name="cat[]" value="{{ $cat->irel__ref_category->Ct_Code }}" />
</tr>
#endif
#endif
#php $catCode = $cat->cc_category_code; #endphp
#endforeach
#endif
</tbody>
I cant find a way because because the data was fetched in table using php , I had refer other post but seems still cant find the way,I hope someone can give some idea . Sorry if my explaination not clear

popup the model on select change option in a table

I have a table and inside it I have a select
<tbody>
#foreach($cheques as $key => $cheque)
<tr data-id="{{ $cheque->id }}">
<td>{{ $cheque->reference }}</td>
<td>{{ $cheque->amount }}</td>
<td>{{ $cheque->owner }}</td>
<td>{{ $cheque->receiver }}</td>
<td>{{ $cheque->date_entree->format('d/m/Y') }}</td>
<td>{{ $cheque->date_payment->format('d/m/Y') }}</td>
<td>
<select name="statue" class="form-control" id="statue">
<option value="0" {{ $cheque->statue == "0" ? 'selected':'' }}>{{ __('messages.cheques.waiting') }}</option>
<option value="1" {{ $cheque->statue == "1" ? 'selected':'' }}>{{ __('messages.cheques.payed') }}</option>
<option value="2" {{ $cheque->statue == "2" ? 'selected':'' }}>{{ __('messages.cheques.not_payed') }}</option>
<option value="3" {{ $cheque->statue == "3" ? 'selected':'' }}>{{ __('messages.cheques.transfered') }}</option>
</select>
</td>
<td>
<i class="fa fa-edit"></i>
<i class="fa fa-trash-alt"></i>
</td>
</tr>
#endforeach
</tbody>
and i want when ever the select statue change i want to pop the model and this is what i done
$("#statue").on('change', function(e){
e.preventDefault();
var tr = $(this).parents('tr');
var id = $(tr).data('id');
var statue = $(this).val();
bootbox.confirm({
size: "small",
message: "{{__('messages.cheques.statue_confirmation')}}",
buttons: {
confirm: {
label:"{{__('messages.buttons.confirm')}}",
className: 'btn-sm btn-danger'
},
cancel: {
label:"{{__('messages.buttons.cancel')}}",
className: 'btn-sm btn-defaul'
}
},
callback: function(result){
if(result){
if(statue == 3){
$("#transfer-cheque-form").find("#id").val(id);
$("#transfer-cheque").modal();
}else{
$.post('change-statue/'+id, {_token:$('meta[name="csrf-token"]').attr('content'), statue:statue}, function(data){
if(data.success){
}
});
}
}
}
});
});
but the problem is the model popup only on the first item on the table otherwise nothing happens
i'm using an template ready who has a dynamic table with pagination
I suspect the issue is you are grabbing it by id of statue. The id is supposed to only correspond with one item on the page (id's should be unique). What you probably want to do is add a class to your select and modify your jquery selector to select that class instead.
<select name="statue" class="form-control" id="statue" class="statue-select">
$(".statue-select").on('change', function(e) {
...
});
Firstly an HTML DOM can only contain single with an ID. You can do :
$('select[name="statue"]').on('change', function(e) {
...
});
If your elements are getting appended/manipulated dynamically on ajax pagination for example, you can do :
$(document).on('change', 'select[name="statue"]', function(e) {
...
});
You should not have a static ID in the select element, you can solve the problem adding a function to listen the select change
function myFunction(event){
//TODO
}
<select onchange="myFunction(event)">

Selector returns undefined

HTML
<form method="post">
{% csrf_token %}
<tr id = "{{ x.id }}">
<td>{{ x.name }}</td>
<td>{{ x.sth }}</td>
<td>{{ x.sth_else }}</td>
<td><button type="submit" name="edit_btn">edit</button></td>
</tr>
</form>
jQuery
$('form').on('submit', function(event){
event.preventDefault();
console.log("Executing script for edit button pressing")
x = $(this).children().first().attr('id');
console.log(x)
});
I'm trying to extract the id from the tr in the html, but whenever i get on the page and see the console output i get: undefined. Any ideas?

Categories

Resources