DEV Community

Cover image for Protect user uploads with Laravel
Wallace Maxters
Wallace Maxters

Posted on • Updated on • Originally published at wallacemaxters.com.br

Protect user uploads with Laravel

In the Laravel, you can protect your uploaded files access, restricting by authenticated user, with a simple code.

Move the uploaded file to local disk:

$path = $request->file('file')->store('photos', ['disk' => 'local']);
return Photo::create(['path' => $path]);
Enter fullscreen mode Exit fullscreen mode
Route::get('photo/{id}', function (Photo $photo) {

    $disk = Storage::disk('local');

    return response($disk->get($photo->path), 200, [
        'content-type' => $disk->mimeType($photo->path)
    ]);

})->middleware('auth');
Enter fullscreen mode Exit fullscreen mode

Discussion (1)

Collapse
brcontainer profile image
Guilherme Nascimento

Does this isolate files between different users? Maybe using something with Illuminate\Auth\Access\HandlesAuthorization or controlling it by the Model itself is better or even using the user ID as a subfolder could solve.