In this article, i will share with you how to make secure and protect your file in laravel and only allow to access authenticated users.
As you know when you work with any web applications then the file uploading functionality is the most important part in that application and also you need to make sure that uploaded files very important to secure from direct access from URL. so, in this article, we will see how to protect and secure files in laravel and only accessible to authenticated users.
You just need to follow the steps.
First, we need to create a controller by running the following artisan command in your laravel application root directory.
php artisan make:controller FileController
then open /app/Http/Controllers/FileController.php
the file and add the following code to it.
namespace App\Http\Controllers;
class FileController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function view($id)
{
$file = storage_path('app/pdfs/') . $id . '.pdf';
if (file_exists($file)) {
$headers = [
'Content-Type' => 'application/pdf'
];
return response()->download($file, 'Test File', $headers, 'inline');
} else {
abort(404, 'File not found!');
}
}
}
Route::get('/preview-file/{id}', 'FileController@view');
i hope you like this small article.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on harsukh21@gmail.com
How to Implement Datepicker in React with Example
Welcome to How to Implement and use Date...API Authentication in Laravel without Using Passport.
Since Laravel 5.3, Laravel Passport is t...How to count all elements or values in an array in PHP
Use the PHP count() or si...How To Connect MongoDB in Express Application
In this article, i will share with you h...How to convert php array to simple xml
In this article, i will share with you h...