Search code examples
laravel-5information-retrieval

Cannot retrieve value passed from controller. Laravel


I'm having trouble passing value from controller to my next controller.

I have used the following code:

In BillController:

return redirect('pdf')->with($sid);

In route:

Route::get('pdf', 'PdfController@invoice');

In my PdfController:

class PdfController extends Controller
{
    public function invoice() 
    {
        $student = Student::where('id',$sid)->first();

        foreach ($student->fees as $fee) {
            $fees= $fee;
        }
    }
}

What is the problem here? Can anyone help me?


Solution

  • Ok there are a number of ways to pass values:

    1. Session Flash message (https://laravel.com/docs/5.2/session)

    First you need to set a key and value with your redirect:

    // Method phpdoc - public function with($key, $value = null)
    return redirect('pdf')->with('sid', $sid);
    

    You can access input values via the \Illuminate\Http\Session object:

    // Have a look at the Session values - dd(Session::all());
    $sid = Session::get('sid');
    

    2. Form submits (https://laravel.com/docs/5.2/requests)

    If you post values, you can access them through the Request object

    public function invoice(Request $request)
        {
            $sid = $request->get('sid');
    

    3 . Via URL

    routes.php

    Route::get('sid/{sid}, 'PdfController@invoice')->name('invoice);
    

    Redirect call (adds $sid into the route):

    return redirect()->route('invoice', [$sid]);
    

    Controller: To get the value just ask in the controller.

    public function index($sid)