I have a page where I store images in a project folder and the name of the image file I store in the DB. So all right, I can save and delete the images in the folder and at the same time delete the data stored in the database. My problem comes when I go back to the page where I select the image (s) once I have deleted some of them. I get the following error and I do not know how to solve it:
{
"message": "",
"exception": "Symfony\Component\HttpKernel\Exception\NotFoundHttpException",
"file": "C:\laragon\www\Opencart\vendor\laravel\framework\src\Illuminate\Routing\RouteCollection.php",
"line": 179,
}
In the console of Chrome I figure error 404 not found.
The controller:
public function store(Request $request)
{
//obtenemos el campo file y el id definido en el formulario
$files = $request->file('imagenes');
$id = $request->input('id');
$destinationPath = public_path() . '\images\productos';
foreach ($files as $file) {
//obtenemos el nombre del archivo
$nombre = $file->getClientOriginalName();
//Movemos el archivo a la carpeta images
$upload_success = $file->move($destinationPath, $nombre);
// Redimensionar imagen
$imagesizer = new imgSizer();
$imagesizer->type = "width";
$imagesizer->max = 160;
$imagesizer->quality = 8;
$imagesizer->square = true;
$imagesizer->prefix = "miniatura_";
$imagesizer->folder = "_min";
$imagesizer->image = "/images/productos/" . $nombre;
$imagesizer->resize();
$infoImagenesSubidas = array("height" => "160px");
$imagenesSubidas = "<img src='/images/productos/_min/miniatura_" . $nombre . "'> height='160px' class='file-preview-image'>";
//Guardamos en la BBDD ruta y el id del producto
Image::create([
'image_path' => $nombre,
'product_id' => $id,
]);
}
$arr = array("file_id" => 0, "overwriteInitial" => true, "InitialPreviewConfig" => $infoImagenesSubidas, "InitialPreview" => $imagenesSubidas);
echo json_encode($arr);
}
public function destroy($id)
{
$image = Image::find($id);
$image->delete();
if (file_exists(public_path('images/productos/' . $image->image_path))) {
unlink(public_path('images/productos/' . $image->image_path));
unlink(public_path('images/productos/_min/miniatura_' . $image->image_path));
}
return redirect()->to('/admin/products/image/store');
}
When I refresh the page the deletion process concludes correctly; Delete the image and return to the page. The error happens when I press the delete button.
File of routes:
Route::get('/', 'WelcomeController@index'); // pagina web
Auth::routes();
Route::group(['middleware' => 'auth'], function () {
Route::get('/admin', 'HomeController@index')->name('admin');
Route::get('/admin/products/', 'ProductController@allProducts')->name('admin.products'); // Muestra todos los productos
Route::get('/admin/active', 'ProductController@index')->name('admin.products.active'); // Muestra los productos activos
Route::get('/admin/inactive', 'ProductController@inactiveProducts')->name('admin.products.inactive'); // Muestra los productos sin stock
Route::get('/admin/show/{id}', 'ProductController@show')->name('products.show'); //Muestra los datos del producto seleccionado para poder ediatrlo
Route::get('/products/{id}/subcategories', 'SubcategoryController@GetSubcategory'); //combos dependientes show-products.balde.php
Route::post('/admin/update/{id}', 'ProductController@update')->name('products.update'); // Actualiza los datos del producto
Route::get('/admin/create', 'ProductController@create')->name('products.create'); //Muestra el formulario para crear un nuevo producto
Route::post('/admin/store', 'ProductController@store')->name('products.store'); // Guardar un nuevo registro
Route::post('/admin/delete/{id}', 'ProductController@destroy')->name('products.destroy'); // eliminar registro
Route::get('/admin/recover', 'ProductController@showProductsDelete')->name('admin.products.recover'); //Muestra la tabla con los elementos de eliminación suave
Route::get('/admin/restore/{id}', 'ProductController@restoreProductsDelete')->name('admin.products.restore'); // Recupera un registro en concreto por su id
Route::get('/admin/image/{id}', 'ImageController@show')->name('admin.products.image'); //Muestra el formulario para subir imágenes
Route::post('/admin/image/store', 'ImageController@store')->name('admin.products.store'); //Guarda imágenes
Route::delete('/admin/products/image/destroy/{id}', 'ImageController@destroy')->name('admin.products.image.destroy');
//Elimina imágenes
});
View:
@extends('admin.layout')
@section('style')
<!-- CSS Fileinput-->
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-fileinput/4.4.5/css/fileinput.min.css" media="all" rel="stylesheet" type="text/css" />
@endsection
@section('content-header')
<section class="content-header">
<h1>
{{$title}}
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
<li class="active">Imágenes</li>
</ol>
</section>
@endsection
@section('content')
@if(Session::has('message'))
<div class="alert alert-success alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-check"></i> Correcto!</h4>
{{Session::get('message')}}
</div>
@endif
<div class="box">
<div class="box-header with-border">
<h3 class="box-title">Seleccionar imágenes</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse" data-toggle="tooltip" title="" data-original-title="Collapse">
<i class="fa fa-minus"></i></button>
<button type="button" class="btn btn-box-tool" data-widget="remove" data-toggle="tooltip" title="" data-original-title="Remove">
<i class="fa fa-times"></i></button>
</div>
</div>
<div class="box-body">
<form enctype="multipart/form-data" method="">
{{csrf_field()}}
<input type="file" name="imagenes[]" id="images" multiple class="file-loading">
</form>
</div>
<!-- /.box-body -->
<div class="box-footer">
Footer
</div>
<!-- /.box-footer-->
</div>
@endsection
@section('scripts-fileinput')
<script>
$('#images').fileinput({
uploadUrl:"{{route('admin.products.store')}}",
language:"es",
theme:"fa",
uploadAsync:false,
minFileCount:1,
maxFileCount:6,
allowedFileExtensions:["jpg","png"],
showRemove:false,
uploadExtraData:{'_token': "{{csrf_token()}}",'id':"{{$product->id}}"},
deleteExtraData:{'_token': "{{csrf_token()}}",'_method':'delete'},
initialPreview:
[
@foreach ($image as $element)
@php
$imagesizer= new imgSizer();
$imagesizer->type= "width";
$imagesizer->max = 200;
$imagesizer->quality=8;
$imagesizer->square=true;
$imagesizer->prefix="miniatura_";
$imagesizer->folder="_min";
$imagesizer->image="/images/productos/".$element->image_path;
$imagesizer->resize();
@endphp
'<img src="{{"/images/productos/_min/miniatura_$element->image_path"}}" height="160px" class="file-preview-image">',
@endforeach
],
initialPreviewConfig:[
@foreach ($image as $element)
{ caption:"{{$element->image_path}}", height:"120px",url:"{{ url('admin/products/image/destroy',$element->id) }}",key:"{{$element->id}}"},
@endforeach
]
})
</script>
@endsection