Download files in Laravel

Let’s see how to download any file in Laravel. You have to write a function to start the download process and to move the file to download location.

public function getDownload()

{

    //PDF file is stored under project/public/download/info.pdf

    $file= public_path(). "/download/info.pdf";

 

    $headers = array(

              'Content-Type: application/pdf',

            );

 

    return Response::download($file, 'filename.pdf', $headers);

}

Laravel 5 and above versions use the below code :

public function getDownload()

{

    //PDF file is stored under project/public/download/info.pdf

    $file= public_path(). "/download/info.pdf";

 

$headers = [

              'Content-Type' => 'application/pdf',

           ];

 

return response()->download($file, 'filename.pdf', $headers);

}

When using these methods do reference the public_path()in order to locate the file.You have to keep the directory private and limit access by creating a method in controller class if you want to  offer real-time monitoring  or control access to the file.