Search code examples
phpsymfonyroutesslug

Mapping slug with database entry


In a symfony project, I have a url pattern like this

/resource/{id}

I can convert this to a sluggified url as

/resource/{slug} 

using documentation given in symfony webiste.

But, I don't know further how to map this {slug} to a record in database. Is there any standard way to do this other than creating a slug variable in entity class and storing one in database then retrieving record using that property?

UPDATE

I don't know how symfony is retrieving data from database. My view action is as follows.

 /**
 * Finds and displays a Resource entity.
 *
 * @Route("/{slug}", name="resource_show")
 * @Method("GET")
 */
public function showAction(Resource $resource)
{
    $deleteForm = $this->createDeleteForm($resource);
    return $this->render('resource/show.html.twig', array(
        'resource' => $resource,
        'delete_form' => $deleteForm->createView(),
    ));
}

I just replaced id with slug in controller after making proper modifications in ResourceEntity. Now symfony is automatically retrieving information from database using slug and it is passed to showAction method..


Solution

  • What you have mentioned is correct, you should generate a Unique Slug from a String ( Ex: Post Title ) , store it in the DB, and find the Entity by Slug

    Example :

    $obj = $repository->findOneBySlug('test-post');
    

    if you want to make the process of creating Slug easy and using well tested library , you can use Sluggable behavior extension for Doctrine.