Take the 2-minute tour ×

Ok, I have looked and looked but cannot seem to find anything on this anywhere. I have a display of results that are paginated beautifully, but they currently display in ascending order. I'd like for them to display in random order. Here is my current controller code:

public function condos() {          

                    'id', 'user_name', 'area_code', 'exchange', 'sln', 'email'),
                'Complex'=>array('id','complex_name', 'realname', 'photo1','photo2','photo3','photo4','photo5', 'complex_website')
                'Unit.type'=>array('condo', 'rentalco'),
$data = $this->paginate('Unit');
$this->set('allcondos', $data);

share|improve this question

2 Answers 2

up vote 3 down vote accepted

For anyone else finding this - the actual answer is to generate a seed (a float between 0 and 1), and save it to the session before the RAND() sort is necessary (in the controller's beforeFilter()). Then:

$this->paginate['order'] = sprintf('RAND(%f), $this->Session->read('seed'));

This preserves the RAND() seed between calls to the paginator, and preserves the overall order of the results between requests.

share|improve this answer
That's great! Can you give a link or show a little code about how to generate a seed? –  huzzah Aug 13 '12 at 13:58
Sure, as soon as you change it to me for the answer. :) The uglified PHP: function random_float($min, $max, $round = 10){ $randomfloat = $min + mt_rand() / mt_getrandmax() * ($max - $min); if($round > 0) $randomfloat = round($randomfloat,$round); return $randomfloat; } –  b. e. hollenbeck Aug 14 '12 at 2:41
that IZ ugly, heh heh. NP, good answer, thank you! –  huzzah Aug 14 '12 at 16:39

This seems to work pretty well on CakePHP 2 for me:

$this->paginate = array(
    'order' => 'RAND()'

This is using the MySQL RAND() function, which Cake just passes on to the database.

EDIT: Now that I think about it, this is not a good idea, because the order is not maintained between pages. I can't think of a good way off the top of my head to randomize the order and maintain continuity between pages. Maybe if you were to shuffle the items on the page with JavaScript?

share|improve this answer
You know what, I just had the wrong syntax before as I had tried 'order' => array('Unit.unitnum'=>'RAND()'), and boy, did THAT break my page like crazy. This was just the thing I needed, thank you!!! –  huzzah Jan 11 '12 at 22:43
Yeah, I see what you mean. I guess I will just resort to sorting my results by something in their table that will make them appear jumbled. Good catch there, thank you! –  huzzah Jan 12 '12 at 1:18
Yeah, you could create an "order" field and have Cake change it periodically with a cron job. –  bjudson Jan 12 '12 at 3:12
See my answer below for an answer that preserves the RAND() order between requests. –  b. e. hollenbeck Aug 12 '12 at 19:08

Your Answer


