I want to show uploaded pdf on Laravel 8

Viewed 35

I need to uploaded a pdf file and show it, but when I tried to show it I get a 404 not found. This is my controller store and show functions. It uploads successfully but doesn't show the pdf.

 public function store(Request $request)
    {
        $request->validate([
            'file' => 'required|mimes:pdf|max:2048',
        ]);              
        $fileModel = new pdf();
            $pdf = $request->file;
            $fileName = time().'.'.$pdf->getClientOriginalExtension();
            $filePath = $pdf->storeAs('public/uploads', $fileName);
            $fileModel->name = $fileName;
            $fileModel->file = '/storage/' . $filePath;
            // storage_path($filePath);'
            $fileModel->save();
            return redirect()->route('pdfs.index')
            ->with('success','File has been uploaded.')
            ->with('pdf', $fileName);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Pdf  $pdf
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
       $fileModel = Pdf::find($id);    

       return view('pdfs.show', compact('fileModel'));
    }
1 Answers

I don't think you have to use the controller or make any new function for this, in your blade you can declare the file path in an anchor tag with target_blank attr, and it will open the file in a new tab. e-g:

<a style="min-width: 100px !important;height:32px;padding:8px 12px;" href="https://example.com/public/file.pdf" target="_blank" type="button" class="btn btn-outline-primary">
                                            View File
                                        </a>
Related