Search code examples
laravelpdflaravel-storage

laravel save pdf no such file or directory


So I want to save a pdf file to a directory on my local server but it keeps saying that the directory does not exist.

So first of all where would you store PDF files that are not accessible to by externals (so not in the public folder).

So this is my code. The download works perfectly.

public function generatePDF()
    {
        $this->mailorder = Session::get('order');
        $this->cart = Session::get('cart');
        $data = [
                    'id' => $this->mailorder->id,
                    'client' => $this->mailorder->Contact,
                    'country' => $this->mailorder->country,
                    'city' => $this->mailorder->city,
                    'street' => $this->mailorder->street,
                    'postal' => $this->mailorder->postal,
                    'phone' => $this->mailorder->phone,
                    'email' => $this->mailorder->email,
                    'dateIn' => $this->mailorder->dateIn,
                    'dateOut' => $this->mailorder->dateOut,
                    'subtotal' => $this->mailorder->subtotal,
                    'tax' => $this->mailorder->tax,
                    'total' => $this->mailorder->total,
                    'cart' => $this->mailorder->cart,
                    'delivery' => $this->mailorder->delivery,
                ];
        $path = "order_{$this->mailorder->id}_{$this->mailorder->Contact}";       
        $pdf = PDF::loadView('pdf.orderConfirmationPdf', $data)->save('storage/app/public/'.$path.'.pdf');
        ;

        return $pdf->download(''.$path.'.pdf');
    }


Solution

  • First of all, you should check if the directory exists with File facade. If it does not exist, you must make the directory.

    if(!File::exists($directory_path)) {
        File::makeDirectory($directory_path);
    }
    

    If the error still occurs, you must force it to make the directory:

    if(!File::exists($directory_path)) {
    
       File::makeDirectory($directory_path, $mode = 0755, true, true);    
    }
    

    After that, you can save the file in that directory.

    Second, if you don't want to save the file in the public directory. you must save it in storage.By simply call storage_path($file_path). this way laravel saves the file under storage/app/public directory.

    after that, you can get the URL of the file according to this answer.