Learn how to configure and use the public_direct
disk in Laravel for direct file access in the public directory without the storage
slug.
Add the public_direct
disk to the filesystems.php
configuration file in the config
directory:
'disks' => [
// Other disks...
'public_direct' => [
'driver' => 'local',
'root' => public_path(),
'url' => env('APP_URL'),
'visibility' => 'public',
],
],
Ensure your APP_URL
environment variable is set correctly in your .env
file:
APP_URL=http://your-domain.com
You can use this custom disk to store and access files directly in the public
directory. Here are some examples:
use Illuminate\Support\Facades\Storage;
// Store a file in the public directory
$filePath = Storage::disk('public_direct')->put('uploads/example.txt', 'File content here');
// Get the URL of the stored file
$fileUrl = Storage::disk('public_direct')->url($filePath);
echo $fileUrl; // Output: http://your-domain.com/uploads/example.txt
Since files are stored directly in the public
directory, you can access them via the URL without any additional slug. For example:
// Assuming the file was stored as 'uploads/example.txt'
$fileUrl = url('uploads/example.txt');
echo $fileUrl; // Output: http://your-domain.com/uploads/example.txt
public
directory, making it straightforward to reference them in your application.storage
slug, making them cleaner and more intuitive.public
, you ensure that the files are accessible via URL.Here’s how you might use this in a Laravel controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class FileController extends Controller
{
public function upload(Request $request)
{
if ($request->hasFile('file')) {
// Store the file directly in the public directory
$filePath = Storage::disk('public_direct')->put('uploads', $request->file('file'));
// Get the URL of the stored file
$fileUrl = Storage::disk('public_direct')->url($filePath);
return response()->json(['url' => $fileUrl]);
}
return response()->json(['error' => 'No file uploaded'], 400);
}
}
In this example, when a file is uploaded, it is stored in the public/uploads
directory, and the URL of the file is returned in the response.
Published By: Krishanu Jadiya
Updated at: 2024-08-03 16:03:42