I am trying to delete a record from my products table, each product has an image. I don't know how to delete the image from the file where it is stored.
Product.js
$(document).ready(function() {
$("#btn-delete").click(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'DELETE',
url: '/product/' + $("#frmDeleteProduct input[name=product_id]").val(),
dataType: 'json',
success: function(data) {
$("#frmDeleteProduct .close").click();
window.location.reload();
},
error: function(data) {
console.log(data);
}
});
});
});
function deleteProductForm(product_id) {
$.ajax({
type: 'GET',
url: '/product/' + product_id,
success: function(data) {
$("#frmDeleteProduct #delete-title").html("¿Do you want to delete this product (" + data.products.name + ")?");
$("#frmDeleteProduct input[name=product_id]").val(data.products.id);
$('#deleteProductModal').modal('show');
},
error: function(data) {
console.log(data);
}
});
}
ProductController.php
I read that I need to put something like this in my controller File::delete('img/products/' . $image); but I don't now how.
public function destroy($id)
{
//File::delete('img/products/' . $image);
$products = Product::destroy($id);
return response()->json([
'error' => false,
'products' => $products,
], 200);
}
You need to pass as a parameter to File::delete() the full path when your image was save. For example, if your images were in a laravel storage path in the subdirectory img/products/, and the name of the image is the id of the product with the .jpg extension, you can do this:
public function destroy($id)
{
$fullImgPath = storage_path("img/products/$id.jpg");
if(File::exists($fullImgPath)) {
File::delete($fullImgPath);
}
$products = Product::destroy($id);
return response()->json([
'error' => false,
'products' => $products,
], 200);
}
But if you have the name of the image in your Product model, you can do this:
public function destroy($id)
{
$product = Product::find($id);
$fullImgPath = storage_path("img/products/".$product->image_name);
if(File::exists($fullImgPath)) {
File::delete($fullImgPath);
}
$product->delete();
return response()->json([
'error' => false,
'products' => $product->id,
], 200);
}
Related
hello guys recently I am developing a new website which have multiple filters so I use the session-based filter with laravel
it is working fine if I use only the Show filter one time but when I switch to another filter, it is sending multiple requests(as much time I repeat the filter)
when someone clicks the filter this code will run
<------- Laravel route where I am sending a request it returns me a HTML file and I am rendering in my div tag where I have all lists ------->
public function filter(Request $request){
$course = Course::query();
if (isset($request->show)) {
Session::put('show',$request->show);
$show = $request->show;
}
if(isset($request->type)){
$course->where('type',$request->type);
}
if (isset($request->ratting)) {
$course->where('ratting','>=',$request->ratting);
Session::put('ratting',$request->ratting);
}
if(isset($request->short_type))
{
$type = $request->short_type;
$course = $this->checkSort($course,$type);
Session::put('short',$type);
}
if (Session::has('search')) {
$search = Session::get('search');
$course->where(function($q) use ($search){
$q->where('title', 'LIKE', '%'.$search.'%')
->orWhere('slug', 'LIKE', '%'.$search.'%')
->orWhere('description', 'LIKE', '%'.$search.'%')
->orWhere('keyword', 'LIKE', '%'.$search.'%');
});
}
if(Session::has('show') && !isset($request->show)){
$show = Session::get('show');
}
if(Session::has('ratting') && !isset($request->ratting)){
$course->where('ratting','>=',Session::get('ratting'));
}
if(Session::has('short') && !isset($request->short)){
$type = Session::get('short');
$course = $this->checkSort($course,$type);
}
$course->select('id', 'title', 'slug', 'description', 'created_at', 'regular_price', 'sell_price', 'thumbnail','ratting','status');
return view('site.courses.ajax-listing',[
'active' => 'courses',
'type' => $request->type,
'courses' => $course->where('status',1)->paginate(isset($show) ? $show : 10),
]);
}
public function checkSort($courses,$type){
if($type == "alphabetically_a_z")
{
$courses->orderBy('title', 'ASC');
}
if($type == "alphabetically_z_a")
{
$courses->orderBy('title', 'DESC');
}
if($type == "date_new_to_old")
{
$courses->orderBy('created_at', 'ASC');
}
if($type == "date_old_to_new")
{
$courses->orderBy('created_at', 'DESC');
}
if($type == "popular")
{
$courses->where('is_popular', 1);
}
return $courses;
}
<------------------------------------------->
In the search input have route where i will send request
<input type="text" hidden id="search-url" value="{{route('ajax-search-course')}}">
<--------- Javascript Code ----->
$(document).ready(function(){
var url = "{{route('ajax-search-course')}}";
var Jobtype = "1";
var value;
$("input[name='RattingRadioDefault']:radio").change(function(){
value = $("[name=RattingRadioDefault]:checked").val();
ajaxFilter(url + "?ratting="+value+ "&type=" + Jobtype);
});
$("input[name='ShowingRadioDefault']:radio").change(function(){
value = $("[name=ShowingRadioDefault]:checked").val();
ajaxFilter(url + "?show=" + value + "&type=" + Jobtype);
});
$("input[name='ShortingRadioDefault']:radio").change(function(){
value = $("[name=ShortingRadioDefault]:checked").val();
console.log("this is value",value,$("[name=ShortingRadioDefault]:checked").val());
ajaxFilter(url + "?short_type=" + value + "&type=" + Jobtype);
});
});
function ajaxFilter(url, data = null) {
//Add Preloader
$('#listing-data').hide();
$('#loading-area').show();
$.ajax({
method: 'GET',
url: url,
data: data,
contentType: "application/json; charset=utf-8",
success: function(data) {
// console.log("this is return data",data);
$('#listing-data').html(data);
$('#loading-area').hide();
$('#listing-data').show();
},
error: function(jqXhr, textStatus, errorMessage) {
// error callback
$('#listing-data').hide();
$('#loading-area').show();
console.log("this is error", errorMessage);
}
});
}
<------------- Javascript pagination page ----------->
//Ajax Paginatio
$(document).one('click', '#ajaxPagination ul li a', function (e) {
console.log("ajax pagination function is running",$(this).attr("href"),"and",$(e).attr("href"));
e.preventDefault();
//Add Preloader
$('#listing-data').hide();
$('#loading-area').show();
var url = $(this).attr("href")+"&"+ "type=" + $('#data_sort_filter').attr('job-type'),
data = '';
e.preventDefault();
$.ajax({
method: 'GET',
url: url,
data: data,
contentType: "application/json; charset=utf-8",
success: function (data) {
$('#listing-data').html(data);
$('#loading-area').hide();
$('#listing-data').show();
},
error: function (jqXhr, textStatus, errorMessage) {
// error callback
$('#listing-data').hide();
$('#loading-area').show();
}
});
});
i was trying to add a multiple filters system with the session. now i have this error pagination function running as much i am repeating filters i want to solve this please help me it is a very important to project for me
Im getting the following error on my Ajax post back {"readyState":0,"status":0,"statusText":"error"}
on my first ajax call but the second one returns data I want.
My C# method (UserSelect) JsonResults shows the data when I put break point
My C# code :
public IActionResult OnPostAreaSelect(string Id)
{
//Generating list for Areas
Guid ModelId = new Guid(Id);
List<ModelArea> modelAreas = _context.ModelArea.Distinct()
.Where(w => w.ModelId == ModelId).OrderBy(o => o.AreaColumn.Name).Include(i => i.AreaColumn).ToList();
return new JsonResult(modelAreas);
}
public IActionResult OnPostUserSelect(string Id)
{
//Generating list for Users
Guid ModelId = new Guid(Id);
List<UserModel> userModels = _context.UserModel
.Where(w => w.ModelId == ModelId).OrderBy(o => o.User.FullName)
.Include(i => i.User)
.ToList();
return new JsonResult(userModels);
}
My JavaScript :
<script type="text/javascript">
$(document).ready(function () {
$("#RepfocusModelDropdown").change(function () {
var Id = $(this).val();
if (Id != null) {
$.ajax({
async: true,
type: "POST",
url: "./Create?handler=UserSelect",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
Id: Id
},
crossDomain: true,
dataType: "json",
success: function (response) {
alert(JSON.stringify(response));
},
error: function (response) {
alert(JSON.stringify(response));
}
});
$.ajax({
type: "POST",
url: "./Create?handler=AreaSelect",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
Id: Id
},
dataType: "json",
success: function (response) {
alert(JSON.stringify(response));
},
error: function (response) {
alert(JSON.stringify(response));
}
});
}
})
})
The second ajax call on my script works fine only the first one returns the error
How can I solve the error
When you work with EntityFramework (or other ORM) there may be problems with serialization because an entity could have some circular references. To avoid this problem a solution is to set serialization settings:
services.AddMvc().AddJsonOptions(opt => {
opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
or:
Newtonsoft.Json.JsonConvert.DefaultSettings = () => new Newtonsoft.Json.JsonSerializerSettings {
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};
I want to create an upload adapter for ckeditor,
I have an issue in my laravel ajax application,
here is my code.
export default class UploadAdapter {
constructor(loader) {
this.loader = loader;
}
upload() {
return new Promise((resolve, reject) => {
let data = new FormData();
data.append('upload', this.loader.file);
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: '/loadImage',
type: 'POST',
data: data,
dataType: 'json',
async:false,
processData: false,
contentType: false,
success: function (data) {
console.log(data.get('upload'));
},
error: function (request, status, error) {
console.log(error);
}
});
});
}
}
I stuck in responding with ajax to laravel controller.
Here is my Controller function:
try {
$file = $request->file('upload');
$uploader = MediaUploader::fromSource($file);
$uploader->setAllowedMimeTypes(['image/jpeg', 'image/gif', 'image/png']);
$uploader->setAllowedExtensions(['jpg', 'jpeg', 'png', 'gif']);
$media = $uploader->upload();
return response()->json([
'uploaded' => true,
'url' => $media->getUrl()
]);
} catch (\Exception $e) {
return response()->json(
[
'uploaded' => false,
'error' => [
'message' => $e->getMessage()
]
]
);
}
Here is my error
SyntaxError: Unexpected end of JSON input
at parse (<anonymous>)
at ajaxConvert (app.js:11826)
at done (app.js:12294)
at XMLHttpRequest.<anonymous> (app.js:12587)
What is the error in my code ???
I cant get the file information in laravel controller..
How can i solve this issue...? Help me Please!!!
You have data - empty
JSON.parse(''); // SyntaxError: Unexpected end of input
Add verification:
data = data != "" ? $.parseJSON(data) : {};
i'm here trying to make a draggable rows for table and update the change in the database, so i follow on tutorial the drag and drop works fine but the changes not save in the database.
this is the tutorial i'm follow
https://shareurcodes.com/blog/create-drag-and-droppable-datatables-using-jquery-ui-sortable-in-laravel
and here my codes
searchController
class SearchController extends Controller {
public function index() {
// $customers = Customer::all();
$customers = Customer::orderBy('order', 'ASC') - > select('id', 'first_name', 'last_name', 'email', 'phone') - > get();
return view('search.search', compact('customers'));
}
public function updateOrder(Request $request) {
$customers = Customer::all();
//$customer = Customer::findOrFail($id);
foreach($customers as $customer) {
$customer - > timestamps = false;
$id = $customer - > id;
foreach($request - > order as $order) {
if ($order['id'] == $id) {
$customer - > update(['order' => $order['id']]);
}
//if($order['id'] = $id){
// $customer->update($request->all());
// }
}
}
return response('Update Successfully', 200);
}
}
search.blade.php
<script type="text/javascript">
$(function() {
$("#table").DataTable();
$("#tablecontents").sortable({
items: "tr",
// cursor: 'move',
opacity: 0.6,
update: function() {
sendOrderToServer();
}
});
function sendOrderToServer() {
let order = [];
$('tr.row1').each(function(index) {
order.push({
id: $(this).attr('data-id'),
position: index + 1
});
});
$.ajax({
type: "POST",
dataType: "json",
url: "{{ url('search.search') }}",
data: {
order: order,
_token: '{{csrf_token()}}'
},
success: function(response) {
if (response.status == "success") {
console.log(response);
} else {
console.log(response);
}
}
});
}
});
</script>
route
Route::post('search/search','searchController#updateOrder');
this is the table
Schema::create('customers', function (Blueprint $table) {
$table->increments('id');
$table->string('first_name');
$table->string('last_name');
$table->string('email')->unique();
$table->string('phone');
$table->integer('order');
$table->timestamps();
when i drag and drop this error in the console
jquery.min.js:4 POST http://adminproject.test/search.search 404 (Not Found)
Can you try changing ajax route like below
url: "{{ url('search/search') }}"
it was a silly mistake,
just change the url in javascript
from
url: "{{ url('search.search') }}",
to
url: "{{ url('search') }}",
When I trying to return the inserted image as json I'm getting error like Cannot use in operator to search for length
Ajax code:
$("#imagesform").submit(function(){
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN':
$('meta[name="_token"]').attr('content')
}
});
$.ajax({
url :"{{url('addImages/').'/'}}" + imagesProductId,
type: 'POST',
data:new FormData($("#imagesform").get(0)),
contentType:false,
processData:false,
success: function (data)
{
//alert(data);
//alert(json.parse(data));
$.each(data, function( index, value ) {
$("#insertedImages").append('<img src="'+value+'" width="75"
height="75" class="upload2"><br>');
alert(value);
});
},
});
return false;
});
Here the images get inserted into db.But while returning to the view and trying to display it with the div tag shows error..(specified above)
Controller:
public function addImages(Request $request,$imagesProductId)
{
$product = Product::create($request->all());
$filenames = array();
if (empty($request->images)) {
return Redirect::back()->withErrors(['msg', 'The Message']);
}
$rules = [
'images'=>'required'
];
$validator = Validator::make($request->all(), $rules);
$result = $validator->fails() ? 'QCFailed' : 'QCVerified';
// echo($result);
foreach ($request->images as $photo) {
$filename = $photo->store('public/uploadedImages');
$filename = substr($filename,22);
$filenames[] = asset('storage/uploadedImages/'.$filename);
ProductsPhoto::create([
'product_id' => $product->id,
'productId'=>$imagesProductId,
'nonliveStatus' => $result,
'filename' => $filename
]);
}
return response()->json($filename);
}
This is my controller function for inserting array of images and I'm returning the same to the view and trying to append it using div tag.