sweet alert destroy method returns null blank page with no request - laravel

i am using sweet alert method framework to show the alert when deleting but when i do this at destroy method return Request() or return $request it returns blank page with no requests or results i don't know why please help
here is my code
my route
Route::resource('brands',App\Http\Controllers\backend\brandController::class);
my table to view brands
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>brand name en</th>
<th>brand name ar</th>
<th>image</th>
<th>action</th>
</tr>
</thead>
<tbody>
#foreach ($brands as $brand)
<tr>
<td>{{$brand->brand_name_ar}}</td>
<td>{{$brand->brand_name_en}}</td>
<td>{{$brand->image}}</td>
<td>edit
<a href="{{route('brands.destroy',$brand->id)}}" id="delete"
class="btn btn-danger">delete</a>
</td>
</tr>
#endforeach
</tbody>
</table>
my sweet alert javascript code
<script>
$(document).ready(function(){
$(function (){
$(document).on('click','#delete',function(e){
e.preventDefault();
var link = $(this).attr('href');
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then((result) => {
if (result.isConfirmed) {
window.location.href = link
Swal.fire(
'Deleted!',
'Your file has been deleted.',
'success'
)
}
});
});
});
});
</script>
my destroy method
public function destroy($id,Request $request)
{
return Request();
$brand = Brand::find($id);
}

Related

Unable to send ajax data to Laravel controller

I'm just trying to send the editable table row data to the controller onClick of the Save button, update that data in the database, and return success.
But I cannot display the data inside the controller function of laravel. Data inside saveMe function is coming as desired as shown in below screenshot but it is not going to the controller
<table id="customersTable" class="table table-bordered table-responsive-md table-striped text-center" style="border-style: solid; border-color:red">
#php
$customersData = Session::get('data');
$issues = Session::get('issues');
#endphp
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Contact</th>
<th>Address</th>
<th>Name</th>
</tr>
</thead>
<tbody id="bodyData">
#foreach ($customersData as $key => $data)
<form action="ajaxform">
<!-- This is our clonable table line -->
<tr>
<td>{{$key}}</td>
<td name="name" class="pt-3-half name" contenteditable="true"
value={{$data['name']}} data-id={{$key}}>
{{$data['name']}}
</td>
<td name="email" class="pt-3-half email" contenteditable="true"
value={{$data['name']}} data-id={{$key}}>
{{$data['email']}}
</td>
<td>
<div class="test">
<span class="table-save">
<button type="button" onclick="saveMe(this)" class=" btn btn-secondary btn-rounded btn-sm my-0 saveBtn">
Save
</button>
</span>
</div>
</td>
</tr>
</form>
#endforeach
</tbody>
</table>
JavaScript function
<script>
function saveMe(params) {
var tr = $(this).closest("tr"); //get the parent tr
var name = $(params).closest("tr").find(".name").text();
var email = $(params).closest("tr").find(".email").text();
console.log(name);
console.log(email);
$.ajax({
url: '/customers/saveSingleRecord',
type: 'GET',
data: {
_token:'{{ csrf_token() }}',
value: {
'name' : name,
'email' : email,
'contact' : contact,
'address' : address,
},
},
success: function(data){
alert("success");
}
});
}
Function inside the controller
class CustomersController extends Controller
{
public function saveSingleRecord(Request $request)
{
// $name = $_GET['name'];
$name = $request->name;
dd($name); // <------------------ Not showing anything
// return response()->json($name);
}
}
Route inside web.php
Route::post('/customers/saveSingleRecord/', [CustomersController::class, 'saveSingleRecord']);
In your ajax request you are passing your data inside value attribute so it's not showing. If you try $request->value['name'] then it will show you the name. If you want to get name directly in request object then pass as like below.
$.ajax({
url: '/customers/saveSingleRecord',
type: 'GET',
data: {
_token:'{{ csrf_token() }}',
'name' : name,
'email' : email,
'contact' : contact,
'address' : address,
},
success: function(data){
alert("success");
}
});
The correct way to send ajax is below
$.ajax({
url: '/customers/saveSingleRecord',
type: 'GET',
data: {
name : name,
email : email,
contact : contact,
address : address,
_token :'{{ csrf_token() }}',
},
success: function(data){
alert("success");
}
});
Basically you set key value pair within data.

Laravel - How to have two datatables in one blade view

I am a laravel beginner. I currently have a project in progressing which need to have two data tables in one page. In my past project, I only know how to make just a datatable to display ine one view page. For now, I need to have Branch Manager Table and Bus Driver Table to be displayed in one view page. For now I only know to display only one data table.
This is the view page
<table id="example1" class="table table-striped first" style="width:100%">
<thead>
<tr>
<th>Branch Manager Name</th>
<th>Contact Number</th>
<th class="col-md-2">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<table id="example2" class="table table-striped first" style="width:100%">
<thead>
<tr>
<th>Bus Driver Name</th>
<th>Contact Number</th>
<th class="col-md-2">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
This is the ajax for Branch Manager
<script type="text/javascript">
$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var table = $('#example1').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('branchManager.list') }}",
columns: [{
data: 'branch_manager_name',
name: 'branch_manager_name'
},
{
data: 'contact_number',
name: 'contact_number'
},
{
data: 'action',
name: 'action',
orderable: true,
searchable: true
},
]
});
});
</script>
This is controller for Branch Manager
public function branchManager(Request $request)
{
$branchManagers = BranchManager::latest()->get();
if ($request->ajax()) {
$data = BranchManager::latest()->get();
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function($row){
$btn = 'Edit';
$btn = $btn.' <i class="far fa-trash-alt btn-outline-danger"></i>';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
return view('admin.employee', compact('branchManagers'));
}
This is the route
Route::get('/employee', [BranchManagerController::class, 'branchManager'])->name('branchManager.list');
Can anyone explain to me how to make it. Like how many controllers do I need? Isit I need to create one more controller for Bus Driver ? Or two tables are just used in one controller? Besides, if it is needed to create one more controller, how the route would looks like? Thanks

Is there a way to update my component dynamically without refreshing the page?

I have a vue component which builds the card up, and within that component is another component that I pass data to with a prop I currently use Swal to as a popup to add a new project to the database however when it finishes adding I have to refresh the page for the data to be visible. The entire reason I wanted to use vue was to not have to refresh the page to view updated data and I haven't been able to figure it out.
This is my Projects.vue
import ProjectItem from './Projects/ProjectItem.vue';
export default {
name: "Projects",
components: {
ProjectItem
},
data() {
return {
projects: []
}
},
methods: {
getProjects () {
axios.get('/api/projects').then((res) => {this.projects = res.data});
},
addProject() {
Swal.queue([{
title: 'Add a New Project?',
html:
'<label for="name" style="color: #000;font-weight: 700">Project Name<input id="name" class="swal2-input"></label>' +
'<label for="description" style="color: #000;font-weight: 700">Project Description<textarea id="description" rows="5" cols="15" class="swal2-input"></textarea></label>',
showCancelButton: true,
confirmButtonText: 'Create Project',
showLoaderOnConfirm: true,
preConfirm: (result) => {
return new Promise(function(resolve, reject) {
if (result) {
let name = $('#name').val();
let desc = $('#description').val();
axios.post('/api/projects', {title:name,description:desc})
.then(function(response){
Swal.insertQueueStep({
type: 'success',
title: 'Your project has been created!'
})
resolve();
})
.catch(function(error){
Swal.insertQueueStep({
type: 'error',
title: 'Something went wrong.'
})
console.log(error);
reject();
})
}
});
}
}])
}
},
mounted () {
this.getProjects();
}
I bind it to ProjectItem in my Project.vue template:
<div class="table-responsive border-top">
<table class="table card-table table-striped table-vcenter text-nowrap">
<thead>
<tr>
<th>Id</th>
<th>Project Name</th>
<th>Team</th>
<th>Date</th>
<th>Preview</th>
</tr>
</thead>
<project-item v-bind:projects="projects" />
</table>
and this is my ProjectItem.vue:
<template>
<tbody>
<tr v-for="project in projects" :key="project.id">
<td>{{ project.id }}</td>
<td>{{ project.title }}</td>
<td><div class="avatar-list avatar-list-stacked">
{{ project.description }}
</div>
</td>
<td class="text-nowrap">{{ project.updated_at }}</td>
<td class="w-1"><i class="fa fa-eye"></i></td>
</tr>
</tbody>
</template>
<script>
export default {
name: "ProjectItem",
props: ["projects"],
}
</script>
You must insert the recently added project to the products array.
If you are able to change the backend code, you could change the response to include the project.
this.projects.push(response.project);

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]);
}

laravel delete is not working

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.

Resources