Search code examples
phplaravelcontrollerstate-management

Laravel: How to persist data between two different requests in a controller?


I have a Laravel controller with two methods: createOrder and getStatus. In the create method, I'm trying to set a property $orderId to store an orderId value, and in the get method, I want to access and display this value using dd($this->orderId).

class XXXPaymentController extends Controller
{
    protected $orderId;
    
    public function createOrder(){
         // ... create an $order
         $this->orderId = $order->id;
    }
    
    public function getStatus(){
          dd($this->orderId); // return null
    }
}

However, since Laravel creates a new instance of the controller for each request, the getStatus method returns null because it's a different instance.

This is specifically a payment request, and I need to persist the $orderId between these two methods. How can I achieve this in Laravel? Is there a recommended way to share data between methods in a controller for different requests?


Solution

  • I think the easiest way of doing this will be by using laravel session helper. On the first method, store the orderId like this

    public function createOrder(){
         // ... create an $order
         session(['orderId' => $order->id]); 
    }
    

    And then on the second one, when you want to retrieve the previously stored order id

    public function getStatus(){
          $orderId = session('orderId');
    }
    

    Note that if you want to pass a default value to the orderId on retrieval, you can transform the line like this :

    $orderId = session('orderId', 'defaultValue'); // The default value can be of any type
    

    PS: Sorry if I've made some grammatical mistake, English is not my main language.