View a Random Record in CakePHP

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.

controllers/posts_controller.php
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(
                                'Post.active'=>1,
                        ),
                        'order' => 'rand()',
                ));
                $this->view($random['Post']['id']);
                $this->render('view');
        }
}

Reply

  • Allowed HTML tags: <b> <br> <p> <a> <strong> <cite> <em> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
  • You may use [img:xx] tags to display uploaded files or images inline.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <css>, <diff>, <drupal5>, <html>, <javascript>, <php>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.

More information about formatting options