View a Random Record in CakePHP

Posted by Mr PHP on

This is a simple action to display a random record. Possibly useful for sites wanting to keep people clicking on something.

The Controller

We find a random record, and then we reuse the current view action and template.


class PostsController extends AppController {
	var $name = 'Posts';

	function random() {
		// $this->Post->contain(); // use this if you are using Containable
		$random = $this->Post->find('first',array(
			'conditions' => array(
			'order' => 'rand()',

Tagged with : CakePHP