How to delete image and file in my database and folder - laravel

when I want to delete data, the data in the rekap table is deleted but the file_rekap table and image_rekap table and those in the folder also don't want to be deleted
Controller Rekap
public function delete_rekap($id){
$data = rekap::findOrfail($id);
$images=image_rekap::where("rekap_id",$data->id)->get();
foreach($images as $image){
if (File::exists("images_rekap/".$image->image)) {
File::delete("images_rekap/".$image->image);
}
}
$files= file_rekap::where("rekap_id",$data->id)->get();
foreach($files as $file){
if (File::exists("rekap_file/".$file->file)) {
File::delete("rekap_file/".$file->file);
}
}
$data->delete();
return redirect()->route('rekap')->with('success','Data berhasil dihapus');
}
this my button
<a href="#" class="btn btn-danger delete m-1" data-id="{{ $row->id}}" data-customer="{{ $row->customer}}" >DELETE</a>
script
$('.delete').click(function(){
var rekapid = $(this).attr('data-id');
var customer = $(this).attr('data-customer');
swal({
title: "Yakin",
text: "Kamu akan menghapus data dengan nama "+customer+" ",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
window.location = "/delete_rekap/"+rekapid+" "
swal("Data Berhasil Terhapus", {
icon: "success",
});
} else {
swal("Data tidak jadi dihapus");
}
});
});
</script>
what steps should i do to fix it

if you want to delete, try
unlink php

Related

Delete confirmation using SweetAlert in ASP.Net Core MVC

How to use sweetalert confirm deleting in my project
i am using asp.net MVC core 5.0
I'm trying to make delete confirmation for category. When user click this button in Index.cshtml it will show delete confirmation for delete data or not, but delete confirmation just appear for while after that data deleted without the confirmation.
Index.cshtml side =
<tr>
<th>ID</th>
<th>Kategori</th>
<th>Sil</th>
<th>Düzenle</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>#item.Id</td>
<td>#item.CategoryName</td>
<td>
<a asp-action="Delete" asp-controller="Category" asp-route-id="#item.Id" class="btn btn-danger" id="delete">Sil</a>
</td>
<td><a asp-action="Edit" asp-controller="Category" asp-route-id="#item.Id" class="btn btn-primary">Güncelle</a></td>
</tr>
}
Controller side =
public IActionResult Delete(int id)
{
var category = _unitOfWork.categoryRepo.Get(x => x.Id == id);
_unitOfWork.categoryRepo.Delete(category);
_unitOfWork.Save();
return RedirectToAction("Index");
}
js side =
<script src="/adminlte/vendor/jquery/jquery.min.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
sweetalert =
<script>
function confirm() {
swal({
title: "Are you sure?",
text: "Once deleted, you will not be able to recover",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
swal("deleted!", {
icon: "success",
});
} else {
swal("category is safe!");
}
});
return false;
}
Merhaba/Hi İbrahim,
Change your code like below;
<td><div><form asp-action="Delete" method="post" asp-controller="Category" asp-route-id="#item.Id"><button type="button" class="btn btn-danger" onclick="return functionConfirm(this)">Delete</button></form>
</div>
</td>
and
#section Scripts{
<script>
function functionConfirm(event) {
const swalWithBootstrapButtons = Swal.mixin({
customClass: {
confirmButton: 'btn btn-success',
cancelButton: 'btn btn-danger'
},
buttonsStyling: false
})
swalWithBootstrapButtons.fire({
title: 'Emin misiniz?',
text: "Bu işlem geri alınamaz!",
icon: 'warning',
showCancelButton: true,
confirmButtonText: 'Evet, sil!',
cancelButtonText: 'Hayır, iptal',
reverseButtons: true,
timer: 3000
}).then((result) => {
if (result.isConfirmed) {
$("form").submit();
swalWithBootstrapButtons.fire({
title: 'Silindi!',
text :'Kategori silindi.',
icon: 'success',
timer:'2000'
}
)
} else if (
/* Read more about handling dismissals below */
result.dismiss === Swal.DismissReason.cancel
) {
swalWithBootstrapButtons.fire(
'İptal edildi',
'',
'error'
)
}
})
}
</script>
}

Trying to upload an image using laravel and vuejs

I have my upload html form like this
<div class="album_single_data settings_data">
<div class="album_single_img">
<figure class="thumbnail thumbnail-rounded">
<img class="main-profile" :src="getprofilepicture()" alt="">
</figure>
</div>
<div class="album_single_text">
<div class="album_btn profile_image">
<div class="btn btn-primary">
<input class="settings-file-upload" type="file" #change="updateProfilePic" ref="file" accept="image/*">
<div class="settings-file-icon">
<span class="material-icons">camera_alt</span>
Upload Profile Picture. (Note: Must Be Less Than 2MB)
</div>
</div>
</div>
</div>
</div>
<div class="form-group">
<button #click="updateInfo" class="btn btn-primary">Update Profile</button>
</div>
This is the vuejs code that handles the form submit/upload method which means anytime i click on the upload button the image uploads. but the problem is that it does not submit
export default {
name: 'Settings',
components: {
//
},
data() {
return{
form: new Form ({
id: '',
username:'',
email: '',
password: '',
name: '',
bio: '',
twitter_handle: '',
facebook_handle: '',
instagram_handle: '',
backgroundPicture: ''
}),
pic: ({
profilePicture: '',
})
}
},
created(){
axios.get("profile")
.then(({ data })=>(this.form.fill(data)))
.then(()=>(this.pic.data))
;
},
methods: {
getprofilepicture()
{
//default avatar pic if there is no photo of user
let profilePicture = "http://localhost:8000/img/profile/user.png";
//returns the current path of the
if (this.pic.profilePicture) {
if (this.pic.profilePicture.indexOf('base64') != -1) {
profilePicture = this.pic.profilePicture;
} else {
profilePicture = 'http://localhost:8000/img/profile/' + this.pic.profilePicture;
}
return profilePicture;
}
return profilePicture;
//let profilePicture = (this.form.profilePicture.length > 200) ? this.form.profilePicture : "http://localhost:8000/img/profile/"+ this.form.profilePicture ;
//return profilePicture;
},
// getBackgroundPic(){
// let backgroundPicture = "http://localhost:8000/img/profile/background.jpg";
// if(this.form.backgroundPicture){
// if(this.form.backgroundPicture.indexOf('base64') != -1){
// backgroundPicture = this.form.backgroundPicture;
// }else {
// backgroundPicture = 'http://localhost:8000/img/profile/'+ this.form.backgroundPicture;
// }
// return backgroundPicture;
// }
// return backgroundPicture;
// },
updateInfo(){
this.$Progress.start();
this.form.put('profile')
.then(()=> {
this.$Progress.finish();
this.$router.go('/profile')
})
.catch(()=>{
this.$Progress.fail()
})
},
updateProfilePic(e){
let file = e.target.files[0];
//console.log(file);
let reader = new FileReader();
if(file['size'] < 2097152){
reader.onloadend = () => {
//console.log('RESULT', reader.result)
this.pic.profilePicture = reader.result;
}
reader.readAsDataURL(file);
}else{
Toast.fire({
icon: 'error',
title: 'Ooops...',
text: 'The file you are trying to upload is more than 2MB',
})
}
},
updateBackgroundPic(e){
let file = e.target.files[0];
//console.log(file);
let reader = new FileReader();
if(file['size'] < 2097152){
reader.onloadend = () => {
this.form.backgroundPicture = reader.result;
}
reader.readAsDataURL(file);
}else{
Toast.fire({
icon: 'error',
title: 'Ooops...',
text: 'The file you are trying to upload is more than 2MB'
})
}
}
}
}
</script>
Anytime i click on the submit button i have this error message: "Undefined offset: 1", exception: "ErrorException",…}
exception: "ErrorException"
and i really do not know the cause of this error.
Below is the PHP Code that handles the server side part of the upload
public function updateProfile(Request $request)
{
$user = auth('api')->user();
$this->validate($request,[
'username' => 'required|string|max:255|unique:users,username,'.$user->id,
'name' => 'max:255',
'email' => 'required|string|email|max:255|unique:users,email,
'.$user->id,
'password' => 'sometimes|required|min:8'
]);
$currentProfilePicture = $user->profilePicture;
if($request->profilePicture != $currentProfilePicture){
$name = time().'.' . explode('/', explode(':', substr($request->profilePicture, 0, strpos($request->profilePicture, ';')))[1])[1];
Image::make($request->profilePicture)->save(public_path('img/profile/').$name);
$request->merge(['profilePicture' => $name]);
$userPhoto = public_path('img/profile/').$currentProfilePicture;
if(file_exists($userPhoto)){
#unlink($userPhoto);
}
}
$user->update($request->all());
}

How to filter a record depending of the user connected using Laravel?

I have the next table..
The IDOP column is a key that I'm using for connect in my app instead of email... I would like to be able for filter the IDOP of each user... So the user should only be able to see the rows with
of its corresponding IDOP, how could I filter only his IDOP?
this is the function of my datatable
$('#user_contactabilidadasesor').DataTable({
processing: true,
"scrollX": true,
//serverSide: true,
ajax: {
url: "{{ route('contactabilidadasesor.index') }}",
},
columns: [
{
data: 'idop',
name: 'l.idop',
className: 'uniqueClassName'
},
{
data: 'idop_asesor',
name: 'idop_asesor',
searchable: false, render: function ( data, type, row ) {
if (data == null){ return ''; }else{return (row['idop_asesor'] + ' ' + row['ape_asesor'])};
},
className: 'uniqueClassName'
}
],
});
And this is my query
public function index(Request $request)
{
if($request->ajax())
{
$data = DB::table('tbl_lista_contactabilidad as a')
->select('a.id','a.postventaatcs_id')
->leftjoin('tbl_equipo_postventaatcs as h','h.id','=','a.postventaatc_id')
->leftjoin('users as l','l.id','=','h.asesor_id')
->select(array('a.id','l.name as idop_asesor','l.apellido as ape_asesor','l.idop'));
return DataTables::of($data)
->addColumn('action', function($data){
$button = '<button type="button" name="edit" id="'.$data->id.'" class="edit btn btn-primary btn-sm">Auditar</button>';
//$button .= ' <button type="button" name="edit" id="'.$data->id.'" class="delete btn btn-danger btn-sm">Delete</button>';
return $button;
})
->rawColumns(['action'])
->make(true);
}
return view('contactabilidadasesor');
}
For filtering you have to use ->where('IDOP', auth()->user()->IDOP) (for single user) of ->whereIn('IDOP', [array of filtering idops]) for multiple IDOPs

Cropped image encrypted data not post in codeigniter on live server. Why?

I have a situation where a user select photo and cropped it.After cropping encoded data passed to hidden input has successfully but when posting my form the image data not post.Only blank page shown.
Same code are working fine on local server. But on live server this happened to me.
Let me share my code. Please guide me where i am doing wrong.
$(".gambar").attr("src", "<?php echo base_url().'assets/img/users/defualt.jpg");
var $uploadCrop,
tempFilename,
rawImg,
imageId;
function readFile(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('.upload-demo').addClass('ready');
$('#cropImagePop').modal('show');
rawImg = e.target.result;
}
reader.readAsDataURL(input.files[0]);
}
else {
swal("Sorry - you're browser doesn't support the FileReader API");
}
}
$uploadCrop = $('#upload-demo').croppie({
viewport: {
width: 150,
height: 150,
type: 'circle'
},
boundary: {
width: 265,
height: 265
},
enforceBoundary: false,
enableExif: true,
enableOrientation: true,
orientation: 4,
});
$('#cropImagePop').on('shown.bs.modal', function(){
$uploadCrop.croppie('bind', {
url: rawImg
}).then(function(){
});
});
$('.item-img').on('change', function () {
imageId = $(this).data('id');
tempFilename = $(this).val();
$('#cancelCropBtn').data('id', imageId);
readFile(this); });
$('#cropImageBtn').on('click', function (ev) {
$uploadCrop.croppie('result', {
type: 'canvas',
format: 'jpeg',
size: {width: 150, height: 150}
}).then(function (resp) {
$('#imageEncoder').val(resp);
$('#item-img-output').attr('src', resp);
$('#cropImagePop').modal('hide');
$('#profile_form').submit();
});
});
<form action="<?= base_url().'userController/update_staff_picture' ?>" method="post" enctype="multipart/form-data" id="profile_form">
<input type="hidden" name="imageEncoder" id="imageEncoder">
<label class="cabinet center-block">
<figure>
<img src="" class="gambar img-responsive img-thumbnail img-circle" id="item-img-output" />
<figcaption><i class="fa fa-camera"></i></figcaption>
</figure>
<input type="file" class="item-img file center-block" name="file_photo"/>
</label>
</form>
User Controller
public function update_staff_picture(){
$data = $this->input->post('imageEncoder');
echo "<pre>";
print_r($data);
exit();
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$image_name = date('ymdgis').'.png';
$req['image']=$image_name;
file_put_contents('./assets/img/users/'.$image_name, $data);
$this->db->set($req);
$this->db->where('userID',$userID);
$this->db->update('users');
redirect(base_url().'staff-profile/'.$_POST['userID']);
}

Laravel Datatables Redirecting to 302

I am using DataTables 1.10.16 and using Ajax I am trying to build the table.
The table works fine in my backend but in frontend I am getting 302 redirect.
But if I call the Ajax URL in the browser it returns the data correctly.
I am not getting where I am going wrong
This is how initialize DataTable
var datatable = $('#reports-info-table');
datatable.DataTable({
"processing": true,
"serverSide": true,
"ajax": BASE_URL + '/user/reported-business-info',
"columns": [{
data: 'slno',
name: 'slno'
},
{
data: 'report',
name: 'report'
},
{
data: 'business_name',
name: 'business_name'
},
{
data: 'show',
name: 'show',
orderable: false,
searchable: false
}
]
});
This is how return the DataTable
return Datatables::of($reports)
->editColumn('report', function ($reports) {
return $reports->vchr_report_message;
})
->editColumn('business_name', function ($reports) {
return $reports->business->vchr_business_name;
})
->addColumn('show', function ($reports) {
if ($reports->int_status == 1) {
return '
<div class="btn-group btn-collection btn-icon-group">
<a class="btn btn-info" data-toggle="tooltip" title="View"> <i class="ua-icon-control-export btn-icon"></i></a>
</div>';
} //If Status is not in active state
else {
return '
<div class="btn-group btn-collection btn-icon-group">
<a class="btn btn-info" data-toggle="tooltip" title="View"> <i class="ua-icon-control-export btn-icon"></i></a>
</div>';
}
})
->rawColumns(['show'])->toJson(true);
I found out that my middleware was stopping the Ajax call and hence getting redirected.
Original Code
if (!$request->ajax() && Auth::check() && (Auth::user()->int_role_id == Roles::ROLE_USER)) {
return $next($request);
}else if (!$request->ajax() && !Auth::check() ){
$url = Request()->path();
Session::put('loginRedirect', $url);
return redirect('/login');
}
Changed TO
if (Auth::check() && (Auth::user()->int_role_id == Roles::ROLE_USER)) {
return $next($request);
}else if (!$request->ajax() && !Auth::check() ){
$url = Request()->path();
Session::put('loginRedirect', $url);
return redirect('/login');
}
Now it Works.

Resources