Search code examples
laravelphpword

Customise the filename in phpword


Is it possible to customize the filename in phpword when I want to download it?

I want that the file takes the prenoms of the exported row.

My code:

public function edit (Stagiaire $stagiaire)
  {
    $id = $stagiaire ->id;
    $desc1 = Stagiaire::find($id);
    $my_template = new \PhpOffice\PhpWord\TemplateProcessor(public_path('templateStagiaire.docx'));
    $my_template->setValue('id, $desc->id);
    $my_template->setValue('prenoms, $desc->prenoms);
    $my_template->setValue('nom, $desc->nom);

    $filename = $stagiaire->prenoms;
    try{
       $my_template->saveAs(storage_path('templateStagiaire.docx'));
       }catch (Réception $e){}
     return response()->download(storage_path('".$filename.".docx));

     }

Need help. Thanks in advance.


Solution

  • Laravel example for downloading file:

    
        public function edit(Stagiaire $stagiaire, $downloadName = null)
        {
            $id = $stagiaire->id;
            $desc = Stagiaire::find($id);
            $my_template = new \PhpOffice\PhpWord\TemplateProcessor(public_path('templateStagiaire.docx'));
            $my_template->setValue('id', $desc->id);
            $my_template->setValue('prenoms', $desc->prenoms);
            $my_template->setValue('nom', $desc->nom);
    
            // save as `prenoms` filename
            $filename = $stagiaire->prenoms;
            try {
                $my_template->saveAs(storage_path("$filename.docx"));
            } catch (Reception $e) {
            }
    
            // if download name is null, then use filename
            $downloadName = $downloadName??$filename;
            
            return response()->download(storage_path("$filename.docx"))
                ->header('Content-disposition','attachment; filename="'.$downloadName.'"');
    
         }
    
    

    Similar Laravel example