CONFA BDC
CONFA BDC

Reputation: 1

Laravel download files

I would like for users to be able to download files in my Laravel application. I have many files inside a public folder, and every file belong to a post. For example, when an admin creates a new post and uploads a file (e.g., like an image in the post), the user can download that image/or pdf.

I've made a button so the user can download a file, but I get the error:

The file "/home/vagrant/Code/BDC/public/uploads/audiobooks/audiobook_location/1" does not exist

And this is my code, with a download button to do the "magic":

public function downloadAudiobook($id)
{
    try
    {
        if (Auth::user())
        {

            $audiobook = public_path('uploads/audiobooks/audiobook_location/' . $id);
            return response()->download($audiobook);
        }
        else
        {
            return redirect()->route('login')->with('validate', 'Por favor inicia sesión para descargar este audiolibro');
        }
    }

    catch(ModelNotFoundException $e)
    {
        Session::flash('flash_message', "Ha ocurrido un error procesando su solicitud, intente mas tarde.");
        return redirect()->back();
    }
}

I know, I pass the ID in the route where are the files, because, I don't know how do it.

And this is my route:

Route::get('audiobooks/download/{id}',['as' => 'audiobooks.download','uses' => 'AudiobookController@downloadAudiobook']);

Upvotes: 0

Views: 2537

Answers (1)

AddWeb Solution Pvt Ltd
AddWeb Solution Pvt Ltd

Reputation: 21681

You should try this may be you understand my answer and its help for you:

public function downloadAudiobook($id)
{
  try
  {
    if (Auth::user())
    {
      //Your table where you store your filename and get your file like

      $resltFile = DB::table('yourTableName')->where('id',$id)->first();  


      $audiobook = public_path().'/uploads/audiobooks/audiobook_location/' . $resltFile->fileName;

      return response()->download($audiobook);
    }
    else
    {
        return redirect()->route('login')->with('validate', 'Por favor inicia sesión para descargar este audiolibro');
    }
  }

  catch(ModelNotFoundException $e)
  {
    Session::flash('flash_message', "Ha ocurrido un error procesando su solicitud, intente mas tarde.");
    return redirect()->back();
  }
}

Upvotes: 1

Related Questions