Problem redirecting laravel

2

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  
    
asked by belkin220 26.03.2018 в 03:31
source

2 answers

1

You are trying to redirect to a route that is by post and to which you are not passing any data by post

return redirect()->to('/admin/products/image/store'); //redirect en la funcion destroy
Route::post('/admin/image/store', 'ImageController@store')->name('admin.products.store'); //Guarda imágenes

The most convenient thing is to send it to this route that you already have declared and it is get

return redirect()->to('/admin/products/'); //redirect en tu funcion destroy
Route::get('/admin/products/', 'ProductController@allProducts')->name('admin.products'); // Muestra todos los productos
    
answered by 29.03.2018 в 02:20
0

I think you're redirecting to a route that is not defined at the moment of deleting the image:

return redirect()->to('/admin/products/image/store');

It should be a valid GET route, for example:

return redirect()->to('/admin/show/' . $product->id);

Or better yet, use a route name:

return redirect()>route('products.show', ['id' => $product->id]);
    
answered by 26.03.2018 в 04:46