Symfony 2 - fetch the last inserted row from table

Instead of hacking code where you want to use it, you can also create a repository method and call it when necessary.

/**
 * Repository method for finding the newest inserted
 * entry inside the database. Will return the latest
 * entry when one is existent, otherwise will return
 * null.
 *
 * @return MyTable|null
 */
public function findLastInserted()
{
    return $this
        ->createQueryBuilder("e")
        ->orderBy("id", "DESC")
        ->setMaxResults(1)
        ->getQuery()
        ->getOneOrNullResult();
}

References: https://symfony.com/doc/current/doctrine.html#querying-for-objects-the-repository


You could get the latest record by using findBy() with order by, limit and offset parameters

$results = $repository->findBy(array(),array('id'=>'DESC'),1,0);
  • First argument is for filter criteria
  • Second argument takes order by criteria
  • Third argument is for limit
  • Fourth argument sets offset

Note it will return you the results set as array of objects so you can get single object from result as $results[0]

FindBy() Examples