Laravel automatic object casting to known data types in JsonResources

Oğuzhan KARACABAY
2 min readSep 14, 2022

--

Photography: Steven Rombauts

First of all, I want to start with explaining the problem; Let’s say we have an Order model for managing orders with two attributes: price and product_name. The price attribute is casted to a Money object.

The Order eloquent model would be look like this:

Order Model

The OrderController will be probably like this:

OrderController

And the OrderResource probably like this:

OrderResource

If we want to fetch an Order record through the OrderController above, we’ll get a JSON like this:

See? The price attribute of the order model is empty ’cause it is casted to a Money object. To solve this issue; You should convert the Money object into an integer or float on every resource that uses this type of money object.

Our Solution

Just import the `AutoCastingJsonResource` trait into your Laravel Resource and override the `casts` method like so:

OrderResource after package implementation

The package will scan all attributes on the resource and run the specified closure for the given attribute instance type. So we get results like this:

As you can see, the Money object is casted to the integer automatically.

Solution For All Resources

But if you pay your attention, you can see that actually we didn’t solve the problem about fixing casting problem for all resources right? It just solves the problem for one Resource, not for all. Okey then, now we can implement a BaseJsonResource which will fix that problem for us:

Now, we can extend our all resources from this BaseJsonResource like this:

After we done with extending BaseJsonResource everything should work fine:

This article co-written by Oğuzhan Karacabay, Yunus Emre Deligöz and available in both English and Turkish.

A github link to AutoCastingJsonResource package : https://github.com/oguzhankrcb/auto-casting-json-resource

--

--

No responses yet