Below is my current code I want to store the pdf inmy files without view it . is it possible ? when user store the data for $bus object on db. I want to store below pdf on my local.
$user = Festivals::where('id', $bus->id)->first();
$pdf = PDF::loadView('user.view', compact('user'));
$name = 'Ref_no' . $user->ref_no . '_' . date('m-d-Y') . '.pdf';
return $pdf->download($name);
if $pdf is a DomPDF object, use its output() method to get pdf content as a string and simply put it in a file;
$content = $pdf->output();
file_put_contents('/path/to/your/file', $content);
You can just do Storage::put($filename, $pdf->output()) if you need.
Related
I need assistance to more understand the concept so I can become a better developer. I want to learn how to refactor the code and erase all duplications.
What's the best practices for image uploads? Renaming them correctly?
I have a block of code that handles two attachments:
if( $request->hasFile('LFImage') ) {
$destination = public_path('app/lostFound/lostItems' . $lostFound->LFImage);
if( File::exists($destination) )
{
File::delete($destination);
}
$file = $request->file('LFImage');
$extension = $file->getClientOriginalExtension();
$filename = $lostFound->LFNumber . '-' . $lostFound->lostItem . '.' . $extension;
$file->move('app/lostFound/lostItems', $filename);
$lostFound->LFImage = $filename;
}
if( $request->hasFile('handoverStatement') ) {
$destination = public_path('app/lostFound/handoverStatements' . $lostFound->handoverStatement);
if( File::exists($destination) )
{
File::delete($destination);
}
$file = $request->file('handoverStatement');
$extension = $file->getClientOriginalExtension();
$filename = $lostFound->lostItem . '-' . $lostFound->LFNumber . '.' . $extension;
$file->move('app/lostFound/handoverStatements', $filename);
$lostFound->handoverStatement = $filename;
}
They're exactly the same except with the upload directory.
How can I make it as a one code block across the entire application with changeable file name and location depending on the form?
Some file names require random strings, how can I "Edit" the random string to the file that was uploaded?
Best practice when uploading and storing files in Laravel is using Storage.
It has all needed methods to work with files, you can save the file like this:
use Illuminate\Support\Facades\Storage;
Storage::put('images/', $request->file('LFImage'));
In the documentation provided above, you can find other examples like renaming and moving files
In order to access these files from web as well, you can use the command php artisan storage:link, which creates a symbolic link to storage folder in your public folder. After you create the symbolic link, you can generate URL to the file like this:
asset('storage/test.txt')
To avoid duplications, you can create a function in your controller to create a file. You will then just call this function with different files to keep the file creation code in one place.
you can simply write this
if ($request->hasFile('logo')) {
deleteImageFromDirectory(setting('logo'), "Settings");
$data['logo'] = uploadImageToDirectory( $request->logo , "Settings");
}
and define uploadImageToDirectory function in your helper functions or create a trait
function uploadImageToDirectory($imageFile, $directory = '' ){
$imageName = $imageFile->getClientOriginalName(); // Set Image name
$imageFile->storeAs("/Images/$directory", $imageName, 'public');
return $imageName;
}
I am trying to generate a thumbnail of the PDF I upload in laravel the thumbnail should be the first page of the PDF. Right now I am manually uploading an image to make the thumbnail like this:
if (request()->has('pdf')) {
$pdfuploaded = request()->file('pdf');
$pdfname = $request->book_name . time() . '.' . $pdfuploaded->getClientOriginalExtension();
$pdfpath = public_path('/uploads/pdf');
$pdfuploaded->move($pdfpath, $pdfname);
$book->book_file = '/uploads/pdf/' . $pdfname;
$pdf = $book->book_file;
}
if (request()->has('cover')) {
$coveruploaded = request()->file('cover');
$covername = $request->book_name . time() . '.' . $coveruploaded->getClientOriginalExtension();
$coverpath = public_path('/uploads/cover');
$coveruploaded->move($coverpath, $covername);
$book->card_image = '/uploads/cover/' . $covername;
}
This can be tedious while entering many data I want to generate thumbnail automatically. I searched many answers but I am not able to find laravel specific. I tried to use ImageMagic and Ghost script but I couldn't find a solution and proper role to implement.
Sorry, can't comment yet!
You can use spatie/pdf-to-image to parse the first page as image when file is uploaded and store it in your storage and save the link in your database.
First you need to have php-imagick and ghostscript installed and configured. For issues with ghostscript installation you can refer this. Then add the package composer require spatie/pdf-to-image.
As per your code sample:
if (request()->has('pdf')) {
$pdfuploaded = request()->file('pdf');
$pdfname = $request->book_name . time() . '.' . $pdfuploaded->getClientOriginalExtension();
$pdfpath = public_path('/uploads/pdf');
$pdfuploaded->move($pdfpath, $pdfname);
$book->book_file = '/uploads/pdf/' . $pdfname;
$pdf = $book->book_file;
$pdfO = new Spatie\PdfToImage\Pdf($pdfpath . '/' . $pdfname);
$thumbnailPath = public_path('/uploads/thumbnails');
$thumbnail = $pdfO->setPage(1)
->setOutputFormat('png')
->saveImage($thumbnailPath . '/' . 'YourFileName.png');
// This is where you save the cover path to your database.
}
$html = $this->load->view('pdf_output_order_details', $pdf, true);
$pdfFilePath = $pdf['data'][0]->first_name . "_" . $pdf['data'][0]->last_name . ".pdf";
ini_set('error_reporting', E_STRICT);
$this->pdf = $this->m_pdf->load('A4-L');
$this->pdf->WriteHTML($html);
$this->pdf->Output($pdfFilePath, "F");
While the pdf file is creating successfully if i change to "F" to "D"
But when attchment comes into picture then it throws an error....
"mPDF error: Unable to create output file: abc.pdf"....
I have set all permission to mpdf lib folder and n number of things done but still it won't work.... Please help guys....
Thank You....
I think your $pdfFilepath should containg not only filename, but filepath too.
From mPdf documentation:
F: save to a local file with the name given by filename (may include a
path).
Try this
$pdfFilePath = $_SERVER['DOCUMENT_ROOT'] . '/files/' . $pdf['data'][0]->first_name . "_" . $pdf['data'][0]->last_name . ".pdf";
Of course make sure you have write access to the files folder.
I write a edit function to update news's info, delete previous image from web root and insert new image:
code is below:
if(unlink($data['News']['image_url']['tmp_name'], WWW_ROOT . 'media/' . $data['News']['image_url']['name'])) //delete image from root and database
{
echo 'image deleted.....'; //success message
}
I can't delete old image and insert new image,how can i correct my function ?
Here your data can not find existing data. use this code
$data1 = $this->News->findById($newsid);
$this->request->data = $data1;
$directory = WWW_ROOT . 'media';
if(unlink($directory.DIRECTORY_SEPARATOR.$data1['News']['image_url']))
{
echo 'image deleted.....';
}
Pass filepath as first argument of unlink():
unlink(WWW_ROOT . 'media/' . $data['News']['image_url']['name'] . '/' . $data['News']['image_url']['tmp_name']);
Also make sure that you have proper permissions to perform this operation in directory containing image.
I have been trying to give a link to admin panel for downloading the product image ordered in sales > order > view. Now its done and I have given the link to download as
www.example.com/namespace/index(mycontroller)/download(myaction)/name/screen.jpg
Inside my controller's action I get the file name as parameter, and I knew the location where the file has been located. Now what should I need to make the image downloadable?
This is my controller action code:
public function downloadAction() {
$name = $this->getRequest()->getParam('name');
$file = Mage::getBaseDir(). DS . 'media' . DS . 'catalog' . DS . 'upload' . DS . $name;
$content = readfile($file);
$this->_prepareDownloadResponse($name, $content);
}
When I try to run the above code I get the following error.
Cannot send headers; headers already sent
Please help
readfile() function reads a file and writes it to the OUTPUT BUFFER and returns the number of bytes read from the file. Here is the solution you may use to replace readfile() function: https://stackoverflow.com/a/10938839/2720986