php - Pass variables from one function to another in the same Controller

326

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}', '[email protected]');
642

Answer

Solution:

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');
    }
}

People are also looking for solutions to the problem: oop - Is there a special object initializer construct in PHP like there is now in C#?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.