0

I'm trying to pass a variable from a controller to some other controller. I'm doing it like this-

SomeController

public function index(){
  $var = 'variable';
  return redirect()->route('toAnotherController')->with('var', $var);
}

Route.php

Route::get('/anotherController', 'AnotherController@index')->name('toAnotherController');

Another Controller

public function index(){
  echo $var;
}

But, this is giving an error "Undefined variable $var". What is going wrong here? Is there any other way to do this?

2 Answers 2

2

This will help you:

Route::get('/anotherController/{var}', 'AnotherController@index')->name('toAnotherController');

public function index($var){
  echo $var;
}

Then use Redirect:

  return redirect()->route('toAnotherController',[$var]);

Good Luck ~~~

Sign up to request clarification or add additional context in comments.

2 Comments

Bare in mind the {var} in the routes means it is required. You can specify optional parameters as {var?} in case this is optional.
I had also tried that method to pass the data, but the problem i was having was in the redirection (while passing the data). It worked, thanks!
2

I hope this is not too late. But I am sure this might help somebody one day!!! In your SomeController Add this instance public $attributes; Add the variable you want to pass to another controller with this

$request->attributes->add(['var' => $request->var]);

You can equally resolve it with the code below on the (Another Controller)controller where you needed it

$var= app('request')->get('var');

N:B - Laravel 5.7. I am not sure of earlier versions

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.