Search code examples
laravelcastingphp-carbon

At what point does a Carbon object turn to string in Laravel?


Looking to write a cast similar to Carbon dates with Laravel, I realized that a Carbon date is converted to a string when passed over to the front-end or blade component.

I have been digging the source code with no luck, does anybody know how this works?

My understanding is that the __toString() method is called on the carbon object at some point but don't know where.

an example would be:


$user = User::first();
// here created_at is a Carbon instance

return response()->with(['created_at' => $user->created_at]);
//once this is on blade created_at is a string

Solution

  • So after more digging found out that json_encode() is responsible for this.

    Therefore if you a json_encode a carbon object, the output is a string. The responses are converted to JSON in laravel's ResponseFactory.

    If you would like to pass a PHP object through a response and would like to only receive a string instead of an object you can utilize JsonSerializable

    class MyClass implements JsonSerializable
    {
     public function jsonSerialize(): string
     {
       return 'something';
     }
    }
    
    $class = new MyClass()
    json_encode($class) // "'something'"
    

    Hope this helps someone in the future