How to pass value from one controller to another in laravel?

by elisha_langworth , in category: PHP Frameworks , 3 days ago

How to pass value from one controller to another in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lottie , 2 days ago

@elisha_langworth 

You can pass values from one controller to another in Laravel by using session flash data or by redirecting with input data.

  1. Using Session Flash Data: In the first controller, store the value in the session flash data:
1
2
3
4
5
6
7
public function firstController()
{
    $value = 'Hello World';
    session()->flash('value', $value);
    
    return redirect()->route('secondController');
}


In the second controller, retrieve the value from the session flash data:

1
2
3
4
5
6
public function secondController()
{
    $value = session()->get('value');
    
    return view('second_view', ['value' => $value]);
}


  1. Using Redirect with Input Data: In the first controller, redirect with input data:
1
2
3
4
5
6
public function firstController()
{
    $value = 'Hello World';
    
    return redirect()->route('secondController')->with('value', $value);
}


In the second controller, retrieve the value from the input data:

1
2
3
4
5
6
public function secondController(Request $request)
{
    $value = $request->input('value');
    
    return view('second_view', ['value' => $value]);
}


Choose the method that best fits your needs and implement it in your Laravel application.