Currently i am developing a website. I am working on CRUD for one of my features and have had no problems up until the delete point. I am using bootstrap modal window as a warning window that pops up to clarify that you wish to delete your account. The code for that view and pop-up window looks like this:
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">
<img src="{{ asset('/uploads/avatars/' . $user->avatar ) }}" style="width:100px; height:100px; float:left;
margin-right:25px ">
<strong>Delete {{$user->name}}'s account?</strong></div>
<div class="card-body">
<form action="delete" method="POST" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-group">
<label for="name">Account Email:</label>
<input type="text" name ="email" value="{{$user -> email}}" class="form-control" readonly>
<div class="form-group">
<div class="text-centre">
<p></p>
<button type="button" data_userid="{{$user->id}}" class="btn btn-danger" data-toggle="modal" data-target="#deleteModal">
Delete
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="deleteModalLabel">Are you sure?</h5>
<form action="{{ route('delete', $user)}} " method="post">
{{method_field('delete')}}
{{csrf_field()}}
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Are you sure you want to permanetly delete your account?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">No, cancel</button>
<button type="submit" class="btn btn-danger">Yes, delete my account</button>
</div>
</form>
</div>
</div>
</div>
My Routes for this page and function look like so:
Route::get('/users/delete', 'Admin\UsersController#index')->name('delete');
Route::delete('admin/users/{user}', 'Admin\UsersController#destroy')->name('users.destroy');
public function destroy($id,Request $request)
{
$user = User::where("id","=",$id)->first();
$user->delete($id);
if ($user->delete())
{
return Redirect::route('home')->with('global', 'Your account has been deleted!');
}
}
ALso, whenever i try to access the page from a dropdown menu with route
<a class="dropdown-item" href="{{ route('users.destroy', $user)}}">
Delete Account
I am met with a blank page, i am sure this is down to the parameter. So just to clarify,
Whenever the modal window pops up and the user hits "Yes, delete my account" nothing happens and the window stays open, and my routing to the page
{{ route('users.destroy', $user)}}
leads to a blank page.
Any help is greatly appreciated!
Change
<form action="{{ route('delete', $user)}} " method="post">
to
<form action="{{ route('delete', ['user' => $user]) }}" method="post">
in modal.
Also
<a class="dropdown-item" href="{{ route('users.destroy', $user)}}">Delete Account </a>
Does not work because it is a GET request. Deleting should be a DELETE request.
So you should open the modal with the click;
Delete Account
According to your configuration it looks like you are using the wrong alias name for the form and anchor. You should switch them.
This is your route config:
Route::get('/users/delete', '[...]')->name('delete');
Route::delete('admin/users/{user}', '[...]')->name('users.destroy');
This is how you should use them:
On your <a/> you should use route('delete')
On your <form/> you should use route('users.destroy', ['user' => $userId]).
And your delete action should look like this:
Delete the user
Logout the current user
Redirect somewhere
public function destroy($id)
{
User::find($id)->delete();
Auth::logout();
return Redirect::route('home')
->with('global', 'Your account has been deleted!');
}
Hope this helps.
This is how we try to delete Laravel
public function destroy(User $user)
{
$user->delete();
return Redirect::route('home')->with('global', 'Your account has been deleted!');
}
u can do it using ajax and sweetalert to it's more interactive for ui
in you blade file
#foreach($user as $u)
Delete
#endforeach
in your blade bottom you can call ajax request
<script>
$(document).on('click','.delete',function()
{
var id = $(this).data('id');
swal({
title: 'Are you sure you want to delete this?',
type: "warning",
showCancelButton: true,
confirmButtonClass: "btn btn-danger m-btn m-btn--pill m-btn--icon m-btn--air",
confirmButtonText: '<span><i class="la la-thumbs-up"></i> Yes, Delete it!</span>',
cancelButtonClass: 'btn btn-secondary m-btn m-btn--pill m-btn--icon m-btn--air',
cancelButtonText: '<span><i class="la la-thumbs-down"></i>No, thanks</span>',
}).then(function(e){
if(e.value){
$.ajax({
url:"{{route('admin.document.delete')}}",
type:'POST',
headers:{ 'X-CSRF-Token' : jQuery('meta[name=csrf-token]').attr('content') },
dataType:'json',
data:{'id':id,_token: '{{csrf_token()}}'},
success:function(response){
var msg = response.msg;
if(response.status=='success'){
//here you can do whatever after delete msg
//for reload u can use - (location.reload);
}
},
});
}
});
});
</script>
and finally in your controller
public function destroy(Request $request)
{
$id=$request['id'];
$delete = manageMultipleDocument::find($id)->delete();
//optional
$flashArr = array(
'msg' => 'Document deleted successfully.',
'status' => 'success'
);
//optional
$request->Session()->flash('succ_message',$flashArr);
//Required return any thing
return $flashArr;
}
Related
I want to open a modal with information about the offer that is grabbed from the database.
Here's what I have so far: (Minimal required code)
Opening modal:
<a href="" data-bs-toggle="modal" data-bs-target="#infoPonuka">
<i class="fa-solid fa-eye spc"> </i>
</a>
Modal:
<div class="modal fade" id="infoPonuka" tabindex="-1" aria-labelledby="infoPonuka" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="infoPonuka">Ponuka - info:</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
#if(isset($_GET['id']))
#foreach ($ponuky AS $item)
#if($item->ID == $_GET['id'])
#php
$ponuka = $item;
#endphp
{{Debug::printr($ponuka, false);}}
#endif
#endforeach
#endif
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Zatvoriť</button>
</div>
</div>
</div>
</div>
When I was doing it, I thought I could maybe just use $_GET to get the ID of the offer, so I can have specific data from an array because every opening modal (the first code block) is shown on every item, so I wanted to make it unique for every button by maybe adding the href="?id={{ $ponuka->ID }}". But I was unable to do so. Does someone have any idea?
You might use ajax request on click of your anchor tag instead of using these attributes data-bs-toggle="modal" data-bs-target="#infoPonuka", and then, in response of your ajax request, set the data in the html of the modal as Passing ajax response data to modal
and then show the modal as:
$("#modalId").modal("show");
right after the line your data is set to modal html.
Make a method in a Controller and a route:
This will retun a redered view.
public function getOffer($offer_id)
{
$offer = Offer::where('id', $offer_id);
$renderedOfferView = view('modal.offer', ['offer' => $offer)->render();
return return response()->json(['status' => 'success', 'renderedOfferView' => $renderedOfferView]);
}
In your blade:
<a href="" data-bs-toggle="modal" data-bs-target="#infoPonuka" onclick="getOffer('{{ $ponuka->ID }}')">
<i class="fa-solid fa-eye spc"> </i>
</a>
<div class="modal fade" id="infoPonuka" tabindex="-1" aria-labelledby="infoPonuka" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="infoPonuka">Ponuka - info:</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body" id="getOfferContent">
<!-- use the getOfferContent id to fill with data -->
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Zatvoriť</button>
</div>
</div>
</div>
</div>
getOffer(id){
$('#getOfferContent').html(''); // clear data
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '/your-getOffer-route',
type: 'GET',
data: {
id: id,
},
success: function( response ) {
$('#getOfferContent').html(response.renderedOfferView); // fill data
},
error: function( response ) {
}
});
}
Do not forgot to set: <meta name="csrf-token" content="{{ csrf_token() }}"> in your layout.blade.php into <head> tag
I'm trying to do the simpliest destroy with Laravel with a little modal, but it always appear a 404 Error.
I'm just doing in 2 parts, the index and the PostController, nothing else:
index (Button)
<button data-toggle="modal" data-target="#deleteModal" data-id="{{ $post->id }}" class="btn btn-danger"> Delete</button>
index (Modal DIV and Script)
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalLabel"></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Are you sure to delete this?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<form method="POST" action="{{ route('post.destroy', 0) }}">
#method('DELETE')
#csrf
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</div>
</div>
</div>
</div>
<script>
window.onload = function() {
$('#deleteModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget)
var id = button.data('id')
var modal = $(this)
modal.find('.modal-title').text('You're going to delete the POST: ' + id)
})
}
</script>
PostController
public function destroy($id)
{
$post = Post::findOrFail($id);
$post->delete();
return back()->with('status', '¡Post deleted!');
}
I believe The second parameter of the helper method route should be an array while you have an integer 0.
Perhaps you mean to do something like this:
<form method="POST" action="{{ route('post.destroy', ['id' => $post->id]) }}">
(my apologies if the syntax is wrong, I'm more experienced with symfony/twig than laravel/blade)
EDIT! LATEST CODE UPDATED, NEW ERROR^
I am currently designing a website which has a feature for users to create an account.
I am encountering problems trying to get the user to be deleted first of all, then for the user to be deleted whilst logged in.
My Users controller looks like so:
public function destroy(Request $request)
{
$user = Auth::user();
Auth::logout();
if ($user->delete())
{
return Redirect::route('\home')->with('global', 'Your account has been deleted!');
}
}
My Modal bootstrap window that opens from a form looks like this;
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="deleteModalLabel">Are you sure?</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<form action="{{route('users.delete', ['user' => Auth::id()])}}" method="Post">
<span aria-hidden="true">×</span>
</button>
</div>
#csrf
#method('delete')
<div class="modal-body">
Are you sure you want to permanetly delete your account?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">No, cancel</button>
<button type="submit" class="btn btn-danger">Yes, delete my account</button>
</div>
</div>
</div>
</div>
The form the modal opens from:
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">
<img src="{{ asset('/uploads/avatars/' . $user->avatar ) }}" style="width:100px; height:100px; float:left;
margin-right:25px ">
<strong>Delete {{$user->name}}'s account?</strong></div>
<div class="card-body">
<form action="delete" method="POST" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-group">
<label for="name">Account Email:</label>
<input type="text" name ="email" value="{{$user -> email}}" class="form-control" readonly>
<div class="form-group">
<div class="text-centre">
<p></p>
<button type="button" class="btn btn-danger" data-toggle="modal" data-target="#deleteModal">
Delete
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
And finally my route looks like this;
Route::post('/users/delete', 'Admin\UsersController#destroy')->name("delete-account");
Any ideas on how to firstly get this working and secondly implement it are welcome. thank you
Please tell us the error you are getting.
The first thing I recognize seeing your code is, that you return on the second line of your method. But after the return, you are still expecting code to run. Unfortunately, this will not work. Code after a return is ignored.
Try to split the methods:
Route::delete('/users/destroy', ['uses' =>'Admin\UsersController#destroy', 'as' => 'users.destroy']);
Route::get('/users/delete', ['uses' =>'Admin\UsersController#delete', 'as' => 'users.delete']);
Form method and request should be like this:
<form action="{{route(users.destroy)}}" method="delete">
Actual problem was the mismatch of route types. You have defined a route of GET type while the form is submitted to a route of DELETE type.
Please replace your code with this one and check:
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="deleteModalLabel">Are you sure?</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<form action="{{route('users.delete', ['user' => Auth::id()])}}" method="Post">
<span aria-hidden="true">×</span>
</button>
</div>
#csrf
#method('delete')
<div class="modal-body">
Are you sure you want to permanetly delete your account?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">No, cancel</button>
<button type="submit" class="btn btn-danger">Yes, delete my account</button>
</div>
</div>
</div>
</div>
And change your route to this
Route::delete('/users/{user}', 'Admin\UsersController#destroy')->name("users.delete");
Your controller lacks an IF-THEN statement
public function destroy(User $user)
{
if($user->id !== Auth::id()) return view('admin.users.delete')->with('user', Auth::user());
Auth::logout();
if ($user->delete())
{
return Redirect::route('\home')->with('global', 'Your account has been deleted!');
}
}
Please replace your code with this one and check:
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="deleteModalLabel">Are you sure?</h5>
<form action="{{route('delete-account'}}" method="Post">
#csrf
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</form>
</div>
<div class="modal-body">
Are you sure you want to permanetly delete your account?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">No, cancel</button>
<button type="submit" class="btn btn-danger">Yes, delete my account</button>
</div>
</div>
</div>
</div>
And change your route to this
Route::post('/users/delete', 'Admin\UsersController#destroy')->name("delete-account");
Your controller lacks an IF-THEN statement
public function destroy(Request $request)
{
$user = Auth::user();
Auth::logout();
if ($user->delete())
{
return Redirect::route('\home')->with('global', 'Your account has been deleted!');
}
}
I have a button to remove a registration type, but the user should only be allowed to remove a registration type if there are no participant registered in that registration type, that is if there are no participants associated with that registration type.
But its not working with code below, it appears:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'project.registration_registration_types' doesn't exist (SQL: select registrations.*, registration_registration_types.registration_type_id as pivot_registration_type_id, registration_registration_types.registration_id as pivot_registration_id from registrations inner join registration_registration_types on registrations.id = registration_registration_types.registration_id where registration_registration_types.registration_type_id = 3)
So I have this HTML that has the link to remove the registration type that when is clicked it shows a modal so the user confirm if he wants or no remove the registration type:
#foreach($registrationType as $rtype)
<div class="form-check">
<input
{{ (old('radiobutton') && old('radiobutton') == $rtype->id) ? 'checked' : '' }}
class="form-check-input radio" type="radio" name="radiobutton"
value="{{ $rtype->id }}" id="{{$rtype->id}}">
<label class="form-check-label" for="exampleRadios1">
{{$rtype->name}} <a data-toggle="modal" class="btn btn-sm btn-outline-light-gray ml-4"
data-target="#removeRtype">
<i class="fa fa-times" aria-hidden="true"></i> Remove</a>
</label>
</div>
<div class="modal fade bd-example-modal-lg" id="removeRtype" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Remove registration type</h5>
<button type="button" class="close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="container">
<div class="row d-flex justify-content-center">
<p>Remove Registration type?</p>
<button class="btn btn-outline-primary" id="cancel_remove" href="#" data-dismiss="modal">No</button>
<a class="btn btn-primary ml-2" id="confirm_remove"
href="{{route('rtype.remove', ['rtypeID' => $rtype->id])}}">Yes</a>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" id="close_login_modal" class="btn btn-primary"
data-dismiss="modal">Close
</button>
</div>
</div>
</div>
</div>
#endforeach
And the method to remove the registration type:
public function destroy($rtypeID)
{
$rtype = RegistrationType::findOrFail($rtypeID);
$registrationsCount = $rtype->registrations->count();
dd($registrationsCount);
if ($registrationsCount == 0) {
$rtype->delete();
Session::flash('success', 'Registration type removed with success.');
return redirect()->back();
} else {
Session::flash('error', 'Is not possible to remove the registration type since there are already participants registered in it.');
return redirect()->back();
}
}
Route:
Route::get('conference/destroy/{rtypeID}/rtypes', [ 'uses' => 'RegistrationTypeController#destroy', 'as'=>'rtype.remove']);
From chat discussion it found that you have wrong pivot table in many to many relation. It should be like this
RegistrationType model:
public function registrations(){
return $this->belongsToMany('App\Registration', 'participants');
}
Registration model:
public function registration_types(){
return $this->belongsToMany('App\RegistrationType', 'participants');
}
Now fetch it like this
$rtype = RegistrationType::with('registrations')->findOrFail($rtypeID);
$registrationsCount = $rtype->registrations->count();
dd($registrationsCount);
I want to delete my record from database by giving an alert box which is bootstrap modal box.
i am using codeigniter, i tried but it did not worked. plz Help..
Here is my Controller:
function deleteImage($id = NULL){
$this->config_mdl->delete_image($id);
$this->session->set_flashdata('msg', 'Image Deletion Successful !!');
}
Here is my Model:
function delete_image($id)
{
return $this->db->delete('tbl_gallery', array('image_id' => $id));
}
Here is my View:
<div id="confirmDelete" class="modal fade" role="dialog" aria-lebelledby="confirmDeleteLebel" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Confirmation</h4>
</div>
<div class="modal-body">
<p>Are you sure want to delete this record?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary btn-sm" id="confirm">OK</button>
<button type="button" class="btn btn-warning btn-sm" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
<div class="caption img-gallery-caption">
<?php
$attributes = array('data-toggle' => 'modal', 'data-target' => '#confirmDelete', 'data-title' => 'Delete Image', 'data-message' => 'Are you sure you want to delete this Image?');
echo anchor('config/editImage', '<i class="glyphicon glyphicon-edit"></i>', $attributes);
echo anchor('config/deleteImage/'.$image->image_id, '<i class="glyphicon glyphicon-trash"></i>');
?>
</div>
Here is my Javascript code:
<script type="text/javascript">
$("#confirmDelete").on('show.bs.modal', function(e){
$(this).find('#confirm').attr('href', $(e.relatedTarget).data('href'));
});
</script>
First ensure that you can go in inside the $("#confirmDelete").on...
You can use ajax in the call
$("#confirmDelete").on('show.bs.modal', function(e){
// Search the 'id'
$.post(
'deleteImage/'+id,
'',
funcion(data){
// some data tha you want to receive from the server
},
'json');
});
you are setting href value of button! button doesn't have href attribute so instead convert your button into anchor tag and it will work!