Skip to content
Advertisement

How can get the name of a image stored in /storage/public if was dynamic name

My problem is that i upload a image on the website in laravel but the database save the path of my local storage with a strange name and extension: Data of my database

The picture was uploaded fine in Storage/app/public but with another name (Like a hash code): Name of the picture

Now, how can get this name in /Storage/Public with a query on a database, or how can upload the image with the original name or by ID?

Code: Form upload:

<form class="formulario" method="POST" enctype='multipart/form-data' action="{{ route('add_taller') }}">
    @csrf
    
    <h4>Añade el titulo correspondiente</h4><input name="titulo">
    <h4>Añade un logo al taller</h4><input type="file" name="icono" class="taller_form {{ $errors->has('name') ? 'alert alert-danger' : ''}}" />
     {!! $errors->first('image', '<p class="alerta">:message</p>') !!}
    <h4>Añade una descripción</h4><textarea name="descripcion" rows="10" cols="50" value="{{ old('textarea') }}"></textarea>
     {!! $errors->first('string', '<p class="alerta">:message</p>') !!}
        
        <button type="submit">Subir a la web</button>
    </form>

In controller:

public function add_taller(Request $request)
{  

    $request->file('icono')->store('public');
    $user = Auth::user();
    DB::table('talleres')->insert([
    'icono' =>$request->icono,
    'titulo' => $request->titulo, 
    'descripcion' => $request->descripcion,
    'user_id' => $user->id,
    'fecha'=> now()]);

     return view('home');

}

View where I need to show the picture:

@foreach($datos as $dato)
<div class="taller">
    <div>
        <img src="{{Storage::url($dato->icono)}}" alt="" srcset=""  class="icon_taller">
    </div>
    <div>
    
        <h4>{{$dato->titulo}}</h4>
        <p>{{$dato->descripcion}}</p>
    </div>
    <div class="botones_area">
        <button>Descarga</button>
        <button>Contacto</button>
    </div>
</div>
@endforeach

Advertisement

Answer

As I can see, you don’t save the path with the file extension.

When you use $request->file('icono')->store('public'); you generate a temporal file and the file extension is determined by Laravel with the MIME type.

What’s about:

public function add_taller(Request $request)
{  

    $path = Storage::putFileAs(
       'public', $request->file('icono'), Str::uuid()
    );

    $user = Auth::user();

    DB::table('talleres')->insert([
        'icono' => $path,
        'titulo' => $request->titulo, 
        'descripcion' => $request->description,
        'user_id' => $user->id,
        'fecha'=> now()]
    );

     return view('home');
}

For the filename, I’ve used Str::uuid function to generate names with a different id. For store files, I’ve used Storage Laravel facade, take a quick look here: https://laravel.com/docs/8.x/filesystem#specifying-a-file-name

What do you think about these changes?

8 People found this is helpful
Advertisement