5

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?

3 Answers 3

3

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.

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

5 Comments

I cant do this it doesn't offers me the solution I want.
Well, then just try to do $this->second(); after calculations are made.
Just insert $this->second(); right after $this->variable = $calculation; in the first method.
No it is not working. I think is not working because it does not know what value to insert.
1

Why don't you use some session variable?

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

and

$value = Session::get('calculation');

Comments

0

you are calling first method in one http call and the second in another one so these two are completely separate run of your application if you want to share a variable in different requests you should use some kind of database

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.