In controller
class acontroller extends Controller
{
private $variable;
public function __construct(){
$this->variable;
}
public function first(){
$calculation = 1 + 1;
$this->variable = $calculation;
return view('something.view');
}
public function second(){
dd($this->variable);
return view('something.view2');
}
}
This is an example. What I'm trying to do is to pass the calculation result in first method to the second. I am expecting in second method inside dd() to show the result 2 but instead of this I am getting null.
What is going wrong and how to fix this?
You need to instantiate (create) $newVar outside of the function first. Then it will be view-able by your other function. You see, scope determines what objects can be seen other objects. If you create a variable within a function, it will only be usable from within that function.
You can pass data to route in laravel using different ways. First, you have to define a web route with parameters and after that, you can pass data to the web route by calling the route method to anchor tag and HTML form attribute.
You really should redesign it. What you could do is create third method and do calculations in it. Then just call this method from first and second ones.
public function first(){
$this->third();
dd($this->variable);
return view('something.view');
}
public function second(){
$this->third();
dd($this->variable);
return view('something.view2');
}
public function third(){
$calculation = 1 + 1;
$this->variable = $calculation;
}
Just insert $this->second();
right after $this->variable = $calculation;
in the first
method.
Why don't you use some session variable?
Session::put('calculation', $this->variable);
and
$value = Session::get('calculation');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With