Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - In controller pass variable to one function to another

Tags:

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?

like image 435
Vasilis Greece Avatar asked May 02 '16 14:05

Vasilis Greece


People also ask

How can I pass variable from one function to another in PHP?

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.

How pass data from controller route in laravel?

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.


2 Answers

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.

like image 187
Alexey Mezenin Avatar answered Oct 03 '22 16:10

Alexey Mezenin


Why don't you use some session variable?

Session::put('calculation', $this->variable);

and

$value = Session::get('calculation');
like image 31
lanlau Avatar answered Oct 03 '22 14:10

lanlau