Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate PDF from an active View Laravel

Tags:

php

laravel

I have a search box when user input roll no, it returns the specific student result. I want to generate PDF of that searched data, that data is in table. enter image description here Main Question : I want to generate PDF for the result of student who has searched for his/her data, so how to generate PDF for that current student result.

Print/PDF Generator Button:

 <a href="{!! url('/getPDF') !!}">Print</a>

PDFController:

class PDFController extends Controller
{
    public function getPDF(Request $request){
            // I want some code here to get the current student result so that I can generate pdf for the current student
            $pdf = PDF::loadView('results.single');
            return $pdf->stream('result.pdf');
    }
}

SearchController:

class ResultsSearchController extends Controller
{
    public function search()
    {
        $keyword = Input::get('keyword');
        $row = Student::where('rollno',$keyword)->first();
        $rollno = $row['rollno'];
        if($keyword == $rollno){
            return View::make('results.single')
            ->with('search',Student::where('rollno',$keyword)
            ->get())->with('keyword',$keyword);
        }else{
            return view('errors.404');
        }
    }
}

Routes.php:

Route::get('/getPDF', 'PDFController@getPDF');

PS : I am using https://github.com/barryvdh/laravel-dompdf

like image 931
Umair Shah Yousafzai Avatar asked Jan 05 '23 17:01

Umair Shah Yousafzai


1 Answers

Try this

First of all change route to

Route::get('/getPDF/{id}', 'yourController@getPDF');

Pass the Searched Student id from single view to PDF view like this

<a href="{!! url('/getPDF', $student->id) !!}"> Print</a>

and in your PDF Controller

public function getPDF(Request $request,$id){
    $student = Student::findOrFail($id);
    $pdf = PDF::loadView('pdf.result',['student' => $student]);
    return $pdf->stream('result.pdf', array('Attachment'=>0));              
}

and get the object in your view like

{!! $student->property !!}
like image 131
Iftikhar uddin Avatar answered Jan 15 '23 23:01

Iftikhar uddin