Laravel中如何将milon/barcode生成的条码图片保存至storage目录?
Hey there! Let's get that barcode saved to your Laravel storage folder properly. Since you already have the barcode generation working and are inserting values into the database first, here's how to tie it all together seamlessly:
Step 1: Prep Your Storage Environment
First, make sure your storage directory has the right permissions and structure:
- Run
chmod -R 755 storage/to ensure Laravel can write to the storage folder. - If you plan to access the barcodes publicly later, run
php artisan storage:linkto create a symbolic link frompublic/storagetostorage/app/public(this lets your frontend serve the images).
Step 2: Modify Your Code to Save the Barcode
After inserting your value into the database, grab that saved value and generate/save the barcode directly to storage. Here's a complete example:
// First, insert your value into the database (your existing code here) $yourModel = YourModel::create([ 'barcode_value' => $yourBarcodeValue, // The value you want to turn into a barcode // Other model fields... ]); // Now generate and save the barcode use Illuminate\Support\Facades\File; use Milon\Barcode\DNS1D; // Initialize the barcode generator $generator = new DNS1D(); // Generate the barcode as a base64-encoded PNG string $barcodeBase64 = $generator->getBarcodePNG($yourModel->barcode_value, 'C128'); // Replace 'C128' with your desired format // Define your storage path - we'll use storage/app/public/barcodes (create folder if missing) $storageDir = storage_path('app/public/barcodes'); if (!File::exists($storageDir)) { File::makeDirectory($storageDir, 0755, true); // Create nested directories if needed } // Create a unique filename to avoid overwrites (use model ID + timestamp for uniqueness) $filename = "barcode_{$yourModel->id}_{time()}.png"; $fullStoragePath = $storageDir . '/' . $filename; // Decode the base64 string and save it to the storage path file_put_contents($fullStoragePath, base64_decode($barcodeBase64)); // Optional: Save the relative path back to your database for future reference $yourModel->barcode_storage_path = "public/barcodes/{$filename}"; $yourModel->save();
Step 3: Access the Saved Barcode (If Needed)
If you need to display the barcode in your frontend, use Laravel's asset() helper (thanks to the storage link we created earlier):
// In a Blade template <img src="{{ asset('storage/' . $yourModel->barcode_storage_path) }}" alt="Barcode">
Quick Troubleshooting Tips
- Permission Issues: If you get write errors, double-check the storage folder permissions or run
php artisan cache:clearto refresh Laravel's file cache. - Base64 Prefix: Some barcode generation methods add a
data:image/png;base64,prefix. If your save fails, strip this first withstr_replace('data:image/png;base64,', '', $barcodeBase64). - Barcode Format: Swap
'C128'with other supported formats like'EAN13','UPCA', or'CODE39'depending on your needs.
内容的提问来源于stack exchange,提问作者Franko Hysaj
相关产品推荐
相关产品推荐

