# CakePHP 4 Search Plugin

> This tutorial will demonstrate the basic usage of the search plugin in CakePHP 4. Search has become an essential tool in any web information system.

- URL: https://www.codethepixel.com/cakephp-4-search-plugin
- Author: Asyraf Wahi Anuar (https://www.codethepixel.com/author/asyraf-wahi-anuar)
- Published: 2020-05-26
- Updated: 2021-11-08
- Category: CakePHP
- Tested with: CakePHP 4.x
- Tags: CakePHP, Plugin, Search, Filter
- Reading time: 4 min

This tutorial will demonstrate the basic usage of the [search plugin](https://github.com/FriendsOfCake/search) in CakePHP 4. Search has become an essential tool in any web information system. There are many methods to execute search functions in a web information system. Using a search plugin will save more time and be easier. Let assume that in this tutorial, I have a users table with attributes (id, name, email, role). The search function is required to search based on name, email and role.

Download search plugin using composer:

```bash
$ composer.phar require friendsofcake/search
```

Load search plugin:

```bash
$ bin/cake plugin load Search
```

or manually load at ...\\src\\Application.php

`src/Application.php`

```php
public function bootstrap(): void
{
	$this->addPlugin('Search');
```

Copy-paste your index page (you also can use search function index) and rename it as search.php at ...\\templates\\Users\\search.php and add the following code to generate the search form before the table:

`templates/Users/search.php`

```php
<?php
	echo $this->Form->create(null, ['valueSources' => 'query']);
	echo $this->Form->control('search', ['placeholder' => 'Wildcards: * and ?']);
	echo $this->Form->control('role', ['options' => ['' => '- All -', '1' => 'Administrator', '2' => 'Moderator']]);

	echo $this->Form->button(__('Search'), ['class' => 'btn btn-primary']);
	if (!empty($_isSearch)) {
		echo ' ';
		echo $this->Html->link(__('Reset'), ['action' => 'search', '?' => array_intersect_key($this->request->getQuery(), array_flip(['sort', 'direction']))], ['class' => 'btn btn-default']);
	}

	echo $this->Form->end();
?>
```

## Add EventInterface in Controller

Add the EventInterface as shown below:

`src/Controller/UsersController.php`

```php
//other codes
namespace App\Controller;

use Cake\Event\EventInterface; //add this
```

## Create Public Function Initialize

`src/Controller/UsersController.php`

```php
public function initialize(): void
{
	parent::initialize();

	$this->loadComponent('Search.Search', [
		'actions' => ['search'],
	]);
}
```

## Create Public Function Search

`src/Controller/UsersController.php`

```php
public function search()
{
	//Download all records at once
	$this->paginate['maxLimit'] = 999;

	$users = $this->paginate($this->Users->find('search', ['search' => $this->request->getQuery()]));

	$this->set(compact('users'));
	$this->set('_serialize', ['users']);
}
```

## Create a Search Manager

If you need need to search more fields, add more attributes in the fields array.

`src/Model/Table/UsersTable.php`

```php
public function initialize(array $config): void
{
	parent::initialize($config);

	//other codes
	
	$this->addBehavior('Search.Search');

	$this->searchManager()
		->value('role')
		->add('search', 'Search.Like', [ 
			'before' => true,
			'after' => true,
			'fieldMode' => 'OR',
			'comparison' => 'LIKE',
			'wildcardAny' => '*',
			'wildcardOne' => '?',
			'fields' => ['name','email','role'],
		]);
}
```

If you've need more fields eg: username, just add in your view and add another -\>value('username') in the search manager.

Below is the sample of the search form output:

> **Screenshot unavailable:** The original screenshot (search.jpg) was lost when the old site moved. The text describes what it showed.

Now you should be able to search your data. That all. Happy coding :)
