Get Single Item in Front End

The view asks the model for the item. In the model, you need the id of the item for querying the database. You can get this id from the URL.

For the model, extend the class with the ItemModel. This class implements the ItemModelInterface. So, you must define a method to get an item - public function getItem($pk = null).

Step 1: Planet Model

src/Model/PlanetModel.php

public function getItem($pk = null)
{
    if ($pk == null)
    {
        $input = Factory::getApplication()->input;
        $pk = $input->get('id', 0, 'int');
    }
        
    $db = Factory::getDbo();
    $query = $db->getQuery(true);
        
    $query->select('*')
        ->from($db->quoteName('#__planets'))
        ->where($db->quoteName('id') . ' = '. $db->quote($pk));
            
    $db->setQuery($query);
        
    $row = $db->loadObject();
        
    return $row;
}

This method gets the primary key from the URL. Then, queries the database table to get the single record object from the database table.

Step 2: View File

src/View/Planet/HtmlView.php

Get the item from the model file.

$this->item = $this->get('Item');

Step 3: Layout File

tmpl/planet/default.php

The layout can now display the item.

<h1><?php echo $this->item->title; ?></h1>
<?php echo $this->item->description; ?>