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?
2
Answers
besides session and cache, you can use a service class that you will inject into your controller’s constructor, preserving the order_id.
create an interface like this,
Then create a service that will implement this service like below,
Then inject this service class into your controller in the constructor.
I think the easiest way of doing this will be by using laravel session helper.
On the first method, store the orderId like this
And then on the second one, when you want to retrieve the previously stored order id
Note that if you want to pass a default value to the orderId on retrieval, you can transform the line like this :
PS: Sorry if I’ve made some grammatical mistake, English is not my main language.