-1

No he podido subir imágenes desde mi aplicación de Laravel, guarda NULL o solamente el nombre de la imagen.

Creo que estoy referenciando únicamente el nombre del archivo y no el archivo como tal.

En mi formulario de HTML tengo lo siguiente: Nótese que es un arreglo de imágenes.

<div class="designs">
  <input class="design" type="file" name="subdesigns[image][]" accept="image/*" placeholder="Sube el diseño">
  <label class="select">
    <select name="subdesigns[spec_id][]">
      <option value="">Formato</option>
      @foreach($specs as $spec)
      <option value="{{$spec->id}}">{{$spec->name}}</option>
      @endforeach
    </select>
  </label>
</div>

Y después en mi SubdesignController guardo de la siguiente manera, para todas las imágenes que se hayan querido agregar:

//Substract array of the images
$subdesigns = $request->input('subdesigns.image');
//Substract array of the specs
$specs = $request->input('subdesigns.spec_id');

//Creations of subdesigns
$i = 0; //To move specs array
foreach ($subdesigns as $subs) {
    $sub = new Subdesign();
    $sub->image = $subs;
    $sub->spec_id = $specs[$i]; //Adding the corresponding spec_id to each subdesign
    $sub->design_id = $design->id;
    $sub->save();
    $i++; // Move to the next spec_id
}

Ahora en mi modelo Subdesign tengo dos mutadores para guardar las imágenes tal y como lo había en un proyecto de Backpack, que funciona perfectamente. Pero cuando acomodé todo para que funcionara con este nuevo proyecto guarda solamente NULL y cuando comento los Mutators solamente guarda el string del nombre del archivo.

public function setImageAttribute($value)
    {
        $user = Auth::user();
        $attribute_name = "image";
        $disk = "public_folder";
        $destination_path = "Disenos/" . $user->id;
        
        $this->uploadFileToDisk($value, $attribute_name, $disk, $destination_path);

        // return $this->{$attribute_name}; // uncomment if this is a translatable field
    }

    public function uploadFileToDisk($value, $attribute_name, $disk, $destination_path)
    {
        $request = \Request::instance();
        // if a new file is uploaded, delete the file from the disk
        if (
            $request->hasFile($attribute_name) &&
            $this->{$attribute_name} &&
            $this->{$attribute_name} != null
        ) { dd("1");
            \Storage::disk($disk)->delete($this->{$attribute_name});
            $this->attributes[$attribute_name] = null;
        }
        // if the file input is empty, delete the file from the disk
        if (is_null($value) && $this->{$attribute_name} != null) {dd("2");
            \Storage::disk($disk)->delete($this->{$attribute_name});
            $this->attributes[$attribute_name] = null;
        }
        // if a new file is uploaded, store it on disk and its filename in the database
        if ($request->hasFile($attribute_name) && $request->file($attribute_name)->isValid()) { dd("3");
            // 1. Generate a new file name
            $file = $request->file($attribute_name);
            $new_file_name = md5($file->getClientOriginalName() . time()) . '.' . $file->getClientOriginalExtension();
            // 2. Move the new file to the correct path
            $file_path = $file->storeAs($destination_path, $new_file_name, $disk);
            // 3. Save the complete path to the database
            $this->attributes[$attribute_name] = $file_path;
            // $this->import($file_path);
        }
    }

También tengo agregado el disk en fylesystems.php de la siguiente manera:

<?php

return [

    'default' => env('FILESYSTEM_DRIVER', 'local'),

    'cloud' => env('FILESYSTEM_CLOUD', 's3'),

    'disks' => [

        'local' => [
            'driver' => 'local',
            'root' => storage_path('app'),
        ],

        'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],

        's3' => [
            'driver' => 's3',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
            'region' => env('AWS_DEFAULT_REGION'),
            'bucket' => env('AWS_BUCKET'),
            'url' => env('AWS_URL'),
        ],
        
        'public_folder' => [
            'driver' => 'local',
            'root' => public_path('images'),
            'url' => '/images',
        ],

    ],

];

Cómo puedo darle solución a esto, no sé qué estoy haciendo mal.

1 respuesta 1

0

La mejor práctica es guardar la ruta de donde se guarda, no la imagen en sí. En la base de datos debería de aparecer, en la columna para la imagen, por ejemplo public/images/image1.jpg

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.