virtual fields cakephp 4

In CakePHP 4, virtual fields allow you to create calculated or derived fields that can be used just like regular fields in your models. These virtual fields are not stored in the database but are dynamically generated when you fetch records from the database.

To define a virtual field in CakePHP 4, you need to specify the field name, the type of the field, and a callback function that calculates the value of the field. The callback function should be defined in your model class and should return the calculated value.

Here's an example of how to define a virtual field in CakePHP 4:

// In your model class
use Cake\ORM\Table;

class MyModelTable extends Table {
    public function initialize(array $config): void {


        $this->virtualFields('full_name', function ($entity) {
            return $entity->first_name . ' ' . $entity->last_name;

In this example, we define a virtual field called 'full_name' that concatenates the 'first_name' and 'last_name' fields of the entity. The callback function takes an entity as an argument and should return the calculated value.

Once you have defined a virtual field, you can use it in your queries and views just like regular fields. For example, you can include it in your find queries or access it in your view templates.

That's it! You now know how to define virtual fields in CakePHP 4.