CakePHP 3 Tutorial 15: Neighbors

Submitted by naidim on Tue, 10/18/2016 - 07:58

In CakePHP 2 there was a handy feature called "neighbors" where you could simply request the neighboring records (previous and next) for easy linking. This is not present in CakePHP 3, probably due to the limited use of such a feature, however, with custom finders you can replicate the functionality.

In your model (e.g. src/Models/Table/UsersTable.php) add the following custom finder:

/**
 * Find neighbors method
 */
public function findNeighbors(Query $query, array $options)
{
    $id = $options['id'];
    $previous = $this->find()
            ->select('id')
            ->order(['id' => 'DESC'])
            ->where(['id <' => $id])
            ->first();
    $next = $this->find()
            ->select('id')
            ->order(['id' => 'ASC'])
            ->where(['id >' => $id])
            ->first();
    return ['prev' => $previous, 'next' => $next];
}

Then you can simply call the function in your Controller.

public function view($id = null)
{
    ...
    $neighbors = $this->Users->find('neighbors', ['id' => $user->id]);
    ...
    $this->set(compact('user', 'neighbors'));
}

And lastly to utilize the neighbor ids in your View:

if ($neighbors['prev']['id']) {
	echo $this->Html->link('<', ['action' => 'view', $neighbors['prev']['id']], ['class' => 'button']);
}

Next: Table Relationships

Add new comment