Im new using laravel with inertia
Version of my laravel is: 9.10.1, Inertia version: 0.11 and Vue: 3.2
I have my class RefundManager
class RefundManager
{
private int $id;
private string $refund;
public function __construct(
int $id,
string $refund,
) {
$this->id = $id;
$this->refund = $refund;
}
public function id(): int
{
return $this->id;
}
public function refund(): string
{
return $this->refund;
}
}
I have in my controller an object of that class, and I can access perfectly at $id and $refund through his respective methods id() and refund(). But when I try to pass it to inertia I receive an empty object. Steps:
return Inertia::render("Ppo/Sat/RefundCases/Index", [
'refund' => $myRefundObject
]);
In my vue component I have declared prop as object:
props: {
'refund': Object
}
And when I change variables $id,$refund to public, then it works.
But when $id and $refund are privates I only receive an empty object and I cannot to access public functions...
How can I make it works with private variables by accessing them through the public methods?
To convert a PHP object to a JS object, you need to convert it to a string with json format.
Laravel does it automatically when you send an object to the view by trying to call toJson()
if defined in the class (by default it is present in Model classes)
So add these two function (will not hurt to add toArray()
too)
/**
* Convert the object instance to an array.
*
* @return array
*/
public function toArray()
{
return [
'id' => $this->id,
'refund' => $this->refund,
];
}
/**
* Convert the object instance to JSON.
*
* @param int $options
* @return string
*
* @throws \Exception
*/
public function toJson($options = 0)
{
$json = json_encode($this->toArray(), $options);
if (JSON_ERROR_NONE !== json_last_error()) {
throw new \Exception(json_last_error_msg());
}
return $json;
}