Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

calin.ionut's avatar

add custom field to query

Hello,

I want to create a simple API and for categories I want to return a json with custom data:

ex:

$categories = $categories->select('CategoryID', 'MenuOrder', 'IsActive', 'Name', 'Slug' )->where($filterCondition)->orderBy($orderBy, $orderType)->paginate($paginate)->appends($queries);

I need 1 more field "Url" - which is not in the DB - I have to generate it using a function that accept CategoryID and Slug for each record.

How can I add custom field (Url) in categories ?

Using a loop for $categories (create an array with the fields...generate the url....etc) I don't think is a good idea (for performance) .... so I was thinking modifying the query - when each row is extracted from the DB ... to generate the Url for each entry directly.

or Is there any better soluttion (faster) ?

The return data is a Json which will be loop on the client (using vue) to display data ......

0 likes
1 reply
johnbaron's avatar

For laravel, there is an option to add custom fields in model. For example add $appends property with array of fields. Then add accessor for that field, for example:

class someModel extends Eloquent {

..
private $appends = [
    'url'
];

public function getUrlAttribute() {
    return str_slug($this->attributes['title'];
}

}

also, it will be appended in json response for that model

Please or to participate in this conversation.