Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass variables from one function to another in the same Controller

Tags:

php

laravel

This is my controller and the function for displaying the view. At the moment I have to repeat all the variables from index to exportPDF. And thus, exporting takes too much time.

class MyController extends Controller {
    public function index($id) {
        $article = Article::find($id);
        return view('articles', compact('article');
    }
}

And the other method which actually exports the pdf. I want it to be shorter and more simple like this:

public function exportPDF($id) {
    $pdf = PDF::loadView('articles', ['article' => $article]);
    return $pdf->setPaper('a4')->setOrientation('portrait')->setOption('margin-top', 0)->download('export-' . $id . '.pdf');
}

How can I pass this $article variable from index to exportPDF function? Btw. the route in web.php (Laravel 5.3) is set up like:

Route::get('exportPDF/{id}', 'MyController@exportPDF');
like image 580
harunB10 Avatar asked Aug 04 '26 11:08

harunB10


1 Answers

You should use it similar like code below

class MyController extends Controller{
    public function index($id){
        $article = Article::find($id);
        $exportedPDF = $this->exportPDF($id,$article);
        return view('articles', compact('article');
    }

    public function exportPDF($id,$article){
        $pdf = PDF::loadView('articles', ['article' => $article]);
        return $pdf->setPaper('a4')->setOrientation('portrait')->setOption('margin-top', 0)->download('export-' . $id . '.pdf');
    }
}
like image 73
KuKeC Avatar answered Aug 06 '26 02:08

KuKeC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!