I am using laravel 7. In my CRUD application, I am having trouble deleting a user record. I have tried a variety of methods which I have left commented out so that you can see what I tried. I am using Sweetalert2 for the confirmation call and when I click confirm, it redirects to the correct page but I do not get a success message nor is the record deleted from the database. I am new to Laravel so if anyone can spot where I may have gone wrong, I would sure appreciate it.
Here are the following relevant codes.
(EDIT OF CODE BELOW!!!)
index.blade.php
#extends('layouts.admin')
#section('content')
<div class="container-fluid mt-5">
<!-- Heading -->
<div class="card mb-4 wow fadeIn">
<!--Card content-->
<div class="card-body d-sm-flex justify-content-between">
<h4 class="mb-2 mb-sm-0 pt-1">
Inicio
<span>/</span>
<span>Registered Users</span>
</h4>
</div>
</div>
<!-- Heading -->
<!--Grid row-->
<!--Grid column-->
<div class="row">
<!--Card-->
<div class="col-md-12 mb-4">
<!--Card content-->
<div class="card">
<!-- List group links -->
<div class="card-body">
<h5>Users Online:
#php $u_total = '0'; #endphp
#foreach ($users as $user)
#php
if($user->isUserOnline()) {
$u_total = $u_total + 1;
}
#endphp
#endforeach
{{ $u_total }}
</h5>
<table id="datatable1" class="table table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Role</th>
<th class="text-center">Online/Offline</th>
<th class="text-center">Banned/Unban</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach ($users as $user)
<tr>
<input type="hidden" name="id" value="{{ $user->id }}">
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>{{ $user->role_as }}</td>
<td>
#if($user->isUserOnline())
<label class="py-2 px-3 badge btn-success" for="">Online</label>
#else
<label class="py-2 px-3 badge btn-warning" for="">Offline</label>
#endif
</td>
<td>
#if($user->isBanned == '0' )
<label class="py-2 px-3 badge btn-primary">Not Banned</label>
#elseif($user->isBanned == '1')
<label class="py-2 px-3 badge btn-danger">Banned</label>
#endif
</td>
<td>
<a class="badge badge-pill btn-primary px-3 py-2" href="{{ url('role-edit/'.$user->id) }}">Editar</a>
<a class="delete badge badge-pill btn-danger px-3 py-2" data-toggle="modal" href="{{ url('user-delete/'.$user->id) }}" data-target="#delete" data-id="{{ $user->id }}">Borrar</a>
</td>
</tr>
#endforeach
</tbody>
</table>
{{-- <div>
{{ $users->links() }}
</div> --}}
</div>
<!-- List group links -->
</div>
</div>
<!--/.Card-->
</div>
<!--Grid row-->
</div>
#endsection
#section('scripts')
<script>
$(document).ready(function() {
$(document).on('click', '.delete', function (e) {
e.preventDefault();
var id = $(this).data('id');
swal.fire({
title: "¿Estás Seguro/a?",
text: "¡No podrás revertir esto!",
icon: 'warning',
showCancelButton: true,
cancelButtonText: 'Cancelar',
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Sí, Borralo!'
},
function() {
$.ajax({
type: "POST",
url: "{{url('/user-delete/{id}')}}",
data: {id:id},
success: function (data) {
//
}
});
});
});
});
</script>
#endsection
Within my web.php (relevant code only)
Route::group(['middleware' => ['auth', 'isAdmin']], function () {
Route::get('/dashboard', function () {
return view('admin.dashboard');
});
Route::get('registered-user', 'Admin\RegisteredController#index');
Route::delete('/user-delete/{id}', 'Admin\RegisteredController#destroy');
Route::get('registered-empresa', 'Admin\EmpresaController#index');
Route::get('registered-empleado', 'Admin\EmpleadoController#index');
Route::get('role-edit/{id}', 'Admin\RegisteredController#edit');
Route::put('role-update/{id}', 'Admin\RegisteredController#updaterole');
Route::post('save-empresa', 'Admin\EmpresaController#store');
Route::get('/edit-empresa/{id}', 'Admin\EmpresaController#edit');
Route::put('/empresa-update/{id}', 'Admin\EmpresaController#update');
Route::get('/edit-empleado/{id}', 'Admin\EmpleadoController#edit');
Route::put('/empleado-update/{id}', 'Admin\EmpleadoController#update');
Route::post('save-empleado', 'Admin\EmpleadoController#store');
});
RegisteredController.php (delete function only)
public function destroy(Request $request, $id)
{
// $user = User::findOrFail($id)->delete();
// return redirect()->back()->with('status', 'Usuario ha sido borrado.');
// $user = User::find($id);
// $user->delete();
// return redirect()->back()->with('status', 'Usuario ha sido borrado.');
User::destroy($id);
}
EDIT!!!
I changed the way I am calling the sweetalert2 but am still getting errors. I changed my delete button in index.blade.php to
<a class="delete badge badge-pill btn-danger px-3 py-2" onclick="deleteConfirmation({{ $user->id }})">Borrar</a>
In the same file, I changed the script to the following:
function deleteConfirmation(id) {
swal.fire({
title: "Borrar?",
text: "¿Estás seguro/a?",
icon: "warning",
showCancelButton: !0,
confirmButtonText: "Sí,Borralo!",
cancelButtonText: "Cancelar",
reverseButtons: !0
}).then(function (e) {
if (e.value === true) {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: 'POST',
url: "{{url('/user-delete')}}/" + id,
data: {_token: CSRF_TOKEN},
dataType: 'JSON',
success: function (results) {
if (results.success === true) {
swal.fire("Done!", results.message, "success");
} else {
swal.fire("Error!", results.message, "error");
}
}
});
} else {
e.dismiss;
}
}, function (dismiss) {
return false;
})
}
I also removed the .ready function as it was causing a conflict with sweetalert2
My Delete function in my RegisteredController now looks like this:
public function delete($id)
{
$delete = User::where('id', $id)->delete();
// check data deleted or not
if ($delete == 1) {
$success = true;
$message = "Usuario borrado exitosamente";
} else {
$success = true;
$message = "Usuario no encontrado";
}
// Return response
return response()->json([
'success' => $success,
'message' => $message,
]);
}
}
And in my web.php, I changed the route to:
Route::post('/user-delete/{id}', 'Admin\RegisteredController#delete');
The sweet alert now pops up and when I click delete, I get the console error:
POST http://ecomsivendo.test/user-delete/4 419 (unknown status)
You also need the headers section for jquery ajax calls.
$.ajax({
type: "POST",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
//.......
Also make sure you have the meta tag in the <head> on the page.
<meta name="csrf-token" content="{{ csrf_token() }}">
Thank you for all those who tried to help me on this. I ended up giving the code another overhaul and this is what I had to do to get it to work.
I had to change my ajax request in the index.blade.php
function deleteConfirmation(id) {
swal.fire({
title: "Borrar?",
text: "¿Estás seguro/a?",
icon: "warning",
showCancelButton: true,
confirmButtonText: "Sí,Borralo!",
cancelButtonText: "Cancelar"
}).then(function (e) {
if (e.value === true) {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: 'POST',
url: "{{url('/user-delete')}}/" + id,
headers: {
'X-CSRF-TOKEN': '<?php echo csrf_token() ?>'
},
data: {"id": id, _method: 'delete'},
dataType: 'JSON',
success: function (results) {
if (results.success === true) {
swal.fire("¡Hecho!", results.message, "success");
setTimeout(function() {
location.reload();
}, 1000);
} else {
swal.fire("¡Error!", results.message, "error");
}
}
});
} else {
e.dismiss;
}
}, function (dismiss) {
return false;
})
}
I am not happy with the setTimout function to get the page to reload and if someone can offer a better solution to avoid reload, I would really appreciate it.
in the controller, I had to change the delete function to the following:
public function delete($id)
{
$delete = User::where('id', $id)->delete();
// check data deleted or not
if ($delete == 1) {
$success = true;
$message = "Usuario borrado exitosamente";
} else {
$success = true;
$message = "Usuario no encontrado";
}
// Return response
return response()->json([
'success' => $success,
'message' => $message,
]);
}
And finally in my web.php, I have the route as:
Route::delete('/user-delete/{id}', 'Admin\RegisteredController#delete');
like I mentioned earlier, I feel like the setTimeout is a hack and I would prefer something a bit more elegant.
In the end, the code does what it is supposed to do and that is delete the entry and update the view.
So I have my car project and I want my cars to be Likeabel. So I installed overtrue likeable with composer require overtrue/laravel-follow, and do everything that is required. I followed tutorial from here.
So this is my code. My CarsController#ajaxRequest:
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function ajaxRequest(Request $request){
$car = Car::find($request->id);
$response = auth()->user()->toggleLike($car);
return response()->json(['success'=>$response]);
}
This is my route in web.php : Route::post('ajaxRequest', 'CarsController#ajaxRequest')->name('ajaxRequest');.
This is my cars index.blade.php:
#foreach($cars as $car)
#if($car->placeni_status != 0)
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12" data-id="{{ $car->id }}">
<div class="auto-listing">
<div class="cs-media auto-media-slider">
#foreach (explode('|', $car->fotografije) as $fotografija)<?php $img = explode('|', $car->fotografije); ?>
<figure>
<img src="/slike_oglasa/{{$fotografija}}" alt="#"/>
<figcaption>
<span class="auto-featured">PREMIUM</span>
<i class="icon-play3"></i>
<div class="cs-photo">8 Photos</div>
</figcaption>
</figure>
#endforeach
</div>
<div class="auto-text">
<span class="cs-categories">Timlers Motors</span>
<div class="post-title">
<h4>{{$car->naslov}}</h4>
<h6>{{$car->naslov}}</h6>
<div class="auto-price"><span class="cs-color">{{$car->cijena}} €</span> <em>{{$car->vrsta_cijene}}</em></div>
<img src="assets/extra-images/post-list-img1.jpg" alt=""/>
</div>
<ul class="auto-info-detail">
<li>Godiste<span>{{$car->godiste}}</span></li>
<li>Kilometraza<span>{{$car->kilometraza}}</span></li>
<li>Mjenjac<span>{{$car->mjenjac}}</span></li>
<li>Gorivo<span>{{$car->gorivo}}</span></li>
</ul>
<div class="btn-list">
<div id="list-view" class="collapse">
<ul>
<li><b>Marka:</b> {{$car->marka}}</li>
<li><b>Model:</b> {{$car->model}}</li>
<li><b>Kubikaza:</b> {{$car->kubikaza}}cc</li>
<li><b>Kilovata:</b> {{$car->kilovata}}kW</li>
<li><b>Konjska snaga:</b> {{$car->konjska_snaga}}ks</li>
<li><b>Registrovan do:</b> {{$car->registracija}}</li>
</ul>
</div>
</div>
<div class="cs-checkbox">
<input type="checkbox" name="list" value="check-listn" id="check-list">
<label for="check-list">Uporedi</label>
</div>
<i id="like{{$car->id}}" class="glyphicon glyphicon-thumbs-up {{ auth()->user()->hasLiked($car) ? 'like-post' : '' }}"></i> <div id="like{{$car->id}}-bs3">{{ $car->likers()->get()->count() }}</div>
<label for="check-list1" style="text-transform: uppercase; color:gray;font-size: 11px;padding-left: 10px;"> {{$car->user->city}}</label>
Pogledajte vise<i class=" icon-arrow-long-right"></i>
</div>
</div>
</div>
#else
And this is script for like system:
<script type="text/javascript">
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('i.glyphicon-thumbs-up, i.glyphicon-thumbs-down').click(function(){
var id = $(this).parents(".panel").data('id');
var c = $('#'+this.id+'-bs3').html();
var cObjId = this.id;
var cObj = $(this);
$.ajax({
type:'POST',
url:'/ajaxRequest',
data:{id:id},
success:function(data){
if(jQuery.isEmptyObject(data.success.attached)){
$('#'+cObjId+'-bs3').html(parseInt(c)-1);
$(cObj).removeClass("like-post");
}else{
$('#'+cObjId+'-bs3').html(parseInt(c)+1);
$(cObj).addClass("like-post");
}
}
});
});
$(document).delegate('*[data-toggle="lightbox"]', 'click', function(event) {
event.preventDefault();
$(this).ekkoLightbox();
});
});
</script>
But when I press like and inspect it in console it shows me error:
jquery.js:4 POST http://localhost:8000/ajaxRequest 419 (unknown status)
and in preview it shows me this:
{message: "CSRF token mismatch.", exception: "Symfony\Component\HttpKernel\Exception\HttpException",…}
message: "CSRF token mismatch."
exception: "Symfony\Component\HttpKernel\Exception\HttpException"
file: "C:\engineering\xampp\htdocs\autoplac\vendor\laravel\framework\src\Illuminate\Foundation\Exceptions\Handler.php"
line: 208
trace: [{,…},…]
You can add the route to App\Http\Middleware\VerifyCsrfToken ,$except array to disable csrf check for specific route.
Or you can submit your csrf token in your ajax request
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
check the doc
I have a modal that has some cities. If the user clicks in a city then in the #conferences div it appears the conferences that have in the column "city" that clicked city. This is working fine.
My doubt is how to, if the user clicks in Country, instead of a city, how to get all conferences, independently of the city because if the user click in Country the results can be of any city.
Do you know how to achieve that?
With value attribute like "" "<a value="">Country</a>" when "Country" is clicked in the console appears:
" {message: "", "exception: "Symfony\Component\HttpKernel\Exception\NotFoundHttpException",…}" in file "/Illuminate/Routing/RouteCollection.php".
ConferenceController method to get the conferences of the clicked city:
public function getConferencesOfCity($slug)
{
$conferences = Conference::whereCity($slug)->get();
return response()->json($conferences);
}
Modal where the city links appears:
<div class="modal-body">
<div class="container">
<ul class="modal-list row">
<li class="col-lg-4 col-md-6 col-sm-12">
<a class="" name="" id="" value="">Country</a>
</li>
#foreach($cities as $city)
<li class="col-lg-4 col-md-6 col-sm-12">
<a class="" name="city" id="{{$city}}">{{$city}}</a>
</li>
#endforeach
</ul>
</div>
</div>
Route:
Route::get('conferences/where/city/{slug}','ConferenceController#getConferencesOfCity')->name('city.conferences');
jQuery ajax request:
$("a[name='city']").on('click', function(){
$('#showCities').html($(this).text());
var city = $(this).attr("id");
$.ajax({
url: '{{ route('city.conferences',null) }}/' + city,
type: 'GET',
success:function(result){
console.log(result)
$('#conferences').empty();
var newConferences='';
var placeholder = "{{route('conferences.show', ['id' => '1', 'slug' => 'demo-slug'])}}";
$.each(result, function(index, conference) {
$('#modal2').modal('hide');
var url = placeholder.replace(1, conference.id).replace('demo-slug', conference.slug);
newConferences += '<div class="col-12 col-sm-6 col-lg-4 col-xl-3 mb-4">\n' +
' <h5 class="card-title">'+conference.name+'</h5>\n' +
<p class="card-text font-size-sm">'+conference.city+'</p>\n' +
' </div>\n';
});
$('#conferences').html(newConferences);
},
error: function(error) {
console.log(error.status)
}
});
});
Laravel View code:
<div class="container" style="display:none;" id="panel1">
<div class="panel panel-default">
<div class="panel-heading" style="color:#0000FF" data-toggle="tooltip" title="Gateways!">
<input type="button" value="Haghway Lite" style="background-color:transparent;border:none;width:100%;height:100%;" name="button1" id="button1"><font size="5"></font>
</div>
<div class="panel-body" align="center">
<img src="haghwaylitecontroller.jpg" width="100" height="100">
</div>
</div>
</div>
This my view code.
Script(ajax):
<script type="text/javascript">
$(document).ready(function() {
$("#button1").click(function(){
var button1 = $(this).val();
if(button1) {
$.ajax({
url: "{{url('panelview').'/'}}"+button1,
type: "GET",
dataType: "json",
success:function(data) {
$.each(data, function(key,value) {
$("#panel1").append('<div "'+ value.panel1 +'"></div>');
});
//alert("success");
}
});
}else{
alert("failed");
}
});
});
In this script code, I calling the ajax function with the button id and trying to pass the value of button to be redirected to the mentioned url and the returned json response to be displayed on the panel body. Here if I am trying to print the button value it alerts NaN
Route:
Route::get('panelview/{button1}','viewController#newProduct');
Controller:
public function newProduct($button1)
{
$users=addModel::select('Desc')->where('Pname',$button1 )->first();;
return json_encode($users);
}
The controller code should fetches the correspoding record based on the value of button and return the response.
I'm trying to remove the record in database via ajax. In the same time I want to delete also the record from the page. So I have this in my HTML
<ul id="comments-list record-'.$row['id'].'" class="comments-list record">
<li>
<div class="comment-main-level">
<div class="comment-box">
<div class="comment-head">
<h6 class="comment-name by-author">'.$row['author'].''</h6>
<a href="?delete='.$row['id'].'" class="del">
<i class="fa fa-trash "></i>
</a>
</div>
</div>
</div>
</li>
</ul>
This is inside the loop which display all records on page. This is the ajax function
$(document).ready(function() {
$('.del').click(function(e) {
e.preventDefault();
var parent = $(this).parent();
$.ajax({
type: 'get',
url: 'delete.php',
data: 'ajax=1&delete=' + parent.attr('id').replace('record-',''),
beforeSend: function() {
parent.animate({'backgroundColor':'#fb6c6c'},300);
},
success: function() {
parent.slideUp(300,function() {
parent.remove();
});
}
});
});
});
And my delete.php is simple delete query
$stmt = $pdo->prepare("DELETE FROM comment where id = :id");
$stmt->bindParam(':id', (int)$id, PDO::PARAM_INT);
$stmt->execute();
Current error is from the ajax when I click on delete on this line index.php:183 Uncaught TypeError: Cannot read property 'replace' of undefined
Uncaught TypeError: Cannot read property 'replace' of undefined
The ajax part is from tutorial since I'm very unfamiliar with js/ajax.
What can be the problem here?
In your function $(this) = <a href="?delete='.$row['id'].'" class="del">.
var parent = $(this).parent(); = <div class="comment-head">
which has no ID. Thus attr('id') returns undefined.
You can select the ul element this way:
var parent = $(this).closest('ul.comments-list.record');
How about this code: (make full use of jquery)
<ul id="comments-list record-'.$row['id'].'" class="comments-list record">
<li>
<div class="comment-main-level">
<div class="comment-box">
<div class="comment-head">
<h6 class="comment-name by-author">'.$row['author'].''</h6>
<i onclick="del(<?=$row['id']?>)" class="fa fa-trash "></i>
</div>
</div>
</div>
</li>
your jquery becomes:
function del(i)
{
$.ajax({
type: 'get',
url: 'delete.php',
data: {'ajax':1,'delete':i},
success: function() {
get_list();
}
});
}
function get_list()
{
//make ajax call to get data from php
}
You are getting undefined because the parent you are fetching is this one:
<div class="comment-head">
As you can see that does not have an id. That is why you are getting undefined.
For reference, I do not believe that there is a replace() method in jQuery. What you might be looking for is a replaceWith() method. Please refer to the documentation for more information.
I do not believe that you need to do a replace anywhere. From what I can understand, you want to pass the row[id] as a parameter on your AJAX call. Instead of trying to do a replace, use data as shown below:
<script
src="https://code.jquery.com/jquery-2.2.4.js"
integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI="
crossorigin="anonymous"></script>
<style>
#comments-list {
border: 1px solid black;
}
</style>
<ul id="comments-list" data-id="1" class="comments-list record">
<li>
<div class="comment-main-level">
<div class="comment-box">
<div class="comment-head">
<h6 class="comment-name by-author">Me</h6>
<a href="?delete=1" class="del">
click here
</a>
</div>
</div>
</div>
</li>
</ul>
<script>
$(document).ready(function() {
$('.del').click(function(e) {
e.preventDefault();
// Grab the id
var commentsBlock = $('#comments-list');
var id = commentsBlock.data('id');
console.log(id);
$.ajax({
type: 'get',
url: 'delete.php',
data: 'ajax=1&delete=' + id,
success: function() {
commentsBlock.slideUp(300,function() {
commentsBlock.remove();
});
}
});
});
});
</script>