Skip to content


Cakephp, display random records

The Controller

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

controllers/posts_controller.php

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

        function random() {
                $random = $this->Post->find('first',array(
                        'conditions' => array(
                                'Post.active'=>1,
                        ),
                        'order' => 'rand()',
                ));
                $this->view($random['Post']['id']);
                $this->render('view');
        }
}
Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks

Posted in CakePHP, PHP, Programming, Web Development.

Tagged with , , .


2 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. red says

    Nice, buy this kind of method should definitely go to the Model (fat models, skinny…)

  2. Grekz says

    nice and clean, thx



Some HTML is OK

or, reply to this post via trackback.

Notify me of follow-up comments via email.


Fork me on GitHub