Laravel download files from a route

David Carr

Laravel Framework PHP & MySQL Tutorials

Laravel makes downloading a server file very easy, in this post I'm going to show a way to download files but only let authenticated users. 

First, a route group is used to set up the auth middleware:

Route::group(['middleware' => 'auth'], function () {
Next create a dedicated download route:
Route::get('download', function () {

Collect a request:

$path = request('f');

Detect the file extension

$extension = pathinfo($path, PATHINFO_EXTENSION);

Create a blocked list array, this is a list of all extensions we won't allow to be downloaded.

$blocked = ['php', 'htaccess'];

If the requested file is not in the blocked array then download it.

if (! in_array($extension, $blocked)) {
    //download the file
    return response()->download($path);
}

Putting it all together:

//only logged in users can download
Route::group(['middleware' => 'auth'], function () {
    
    //respond to route /download?f=path
    Route::get('download', function () {

        //get the GET request
        $path = request('f');

        //look at the extension of the file being requested
        $extension = pathinfo($path, PATHINFO_EXTENSION);

        //create an array of items to reject being downloaded
        $blocked = ['php', 'htaccess'];

        //if the requested file is not in the blocked array
        if (! in_array($extension, $blocked)) {
            //download the file
            return response()->download($path);
        }
    });
});

 

Fathom Analytics $10 discount on your first invoice using this link

David Carr - Laravel Developer

Hi, I’m David Carr

A Senior Developer at Vivedia
I love to use the TALL stack (Tailwind CSS, Alpine.js, Laravel, and Laravel Livewire)

I enjoy writing tutorials and working on Open Source packages.

I also write books. I'm writing a new book Laravel Testing Cookbook, This book focuses on testing coving both PestPHP and PHPUnit.

Sponsor me on GitHub

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Laravel Testing Cookbook

Help support the blog so that I can continue creating new content!

Fathom Analytics $10 discount on your first invoice using this link

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2006 - 2023 DC Blog. All code MIT license. All rights reserved.