CakePHP 4 Concatenation

CakePHP 4 Concatenation

In formal language theory and computer programming, concatenation is the operation of joining character strings end-to-end. For example, the concatenation of "snow" and "ball" is "snowball". The most popular concatenation in programming is combining first and last name field to form a full name. This tutorial show the code of concatenation in CakePHP 4.


Let assume that you have users and documents table. The user's table contains (id, name, email, role, status) and document's table contains (id, user_id, title, attachment). In the user table, you can select the name of the users as an input. However, it will only show either id or name(depend on your DisplayField() value). To stitch the name and role value (eg: Muhammad - Administrator), use the following code in your controller (eg: public function add).

$users = $this->Documents->Users->find('list', [
	'valueField' => function ($row) {
		return $row['fullname'] . ' - ' . $row['role'];
	}
]);
$this->set(compact('documents', 'users'));


That all. Happy coding :)