In certain situations it’s useful to calculate extra fields from within your eloquent models. For instance it may be useful to calculate distance for a model that has coordinate fields.
This can be achieved by using eloquents scope functions to add the additional field when required.
First create a model with its base fields.
Then to create the distance field, we can add a scope function that uses the Haversine formula to calculate the distance in miles between two sets of latitude and longitude coordinates.
But now when the model is called with the distance field the selectRaw query has overwritten the models original select query. As a result the model will now only contain the distance field.
We can correct this by overwriting the eloquent models newQuery function which is called at the start of any new query involving the model. Here we can re-add the “select *” query.
Now when the model is called all base and calculated fields are returned.