search

Home  >  Q&A  >  body text

How to pass object with private variables from Laravel to Inertia

I'm new to using Laravel's inertia

My laravel version is: 9.10.1, Inertia version: 0.11, 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 an object of this class in my controller and I have perfect access to $id and $refund via their respective methods id() and returned(). But when I try to pass it to inertia, I receive an empty object. step:

return Inertia::render("Ppo/Sat/RefundCases/Index", [
   'refund' => $myRefundObject
]);

In my vue component, I have declared the prop as an object:

props: {
  'refund': Object
}

When I change the variables $id,$refund to public, it works.

But when $id and $refund are private, I only receive an empty object and have no access to the public functions...

How can I make it work with private variables by accessing them through public methods?

P粉986937457P粉986937457304 days ago588

reply all(1)I'll reply

  • P粉018548441

    P粉0185484412024-03-27 00:44:54

    To convert a PHP object to a JS object, you need to convert it to a json format string.

    Laravel does this automatically when you send an object (if defined in a class) to the view by trying to call toJson() (by default it exists in the Model class)

    So adding these two functions (adding toArray() doesn’t hurt either)

    /**
     * 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;
    }

    reply
    0
  • Cancelreply