You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
12 Hrs
2 Min
27 Seg
Curso Pr谩ctico de Symfony

Curso Pr谩ctico de Symfony

Profesor Italo Morales F

Profesor Italo Morales F

Datos falsos cercanos al mundo real

9/22
Resources

How to automate the generation of slugs in Categories and Publications?

The desire to improve and get closer to more real data is a constant in professional programming. In this process, one of the common needs is to automate the generation of slugs from a name or title in content platforms. Slugs not only make URLs more user-friendly, but also improve the organization and SEO of the website. This process can be automated in both categories and publications, thus achieving a more natural integration.

How to configure the slug field in Posts?

To begin with, let's automate the slug in Posts. Instead of typing it manually each time, let's configure the system to generate it automatically from the title.

  • Go to the Publications schema.
  • Import the class needed for slug handling.
  • Change the type of the slug field to slug, basing it precisely on the title field.
# Example of change in the schema of a Publicationclass Publication(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True)

So, when we create a new publication, the slug is automatically generated, reflecting what is written in the title.

How to replicate this process in Categories?

Similar to the Post process, Categories also benefit from automation. This can be adjusted by changing the field type and ensuring that the slug is based on the category name.

  • Copy and paste the Publications configuration.
  • Modify the name field, setting the slug based on this field:
# Example of change in the schema of a Categoryclass Category(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True).

This modification guarantees a unique representation in the routes, avoiding duplication since each category will have its own unique slug.

How to improve validation on fake data generation?

When working with fake data to test our system, it is essential that these are as close as possible to the real data. This includes string manipulation and setting up unique names and slugs. We will use functions such as string to lower and replace.

  • Store the result in a variable.
  • Convert the string to lower case and replace spaces with hyphens:
# Example of name to slug conversionname = "Example category"slug = name.lower().replace(" ", "-").

In addition, it is important to avoid duplicates in slugs for categories with similar names. Therefore, implementing custom logic within the fake data generation methods is crucial.

What else to consider in the system configuration?

It is possible that when working with unique words, duplicates may occur if we do not implement a check. This detail must be considered in the categories. In the case of phrases, such as titles in publications, the probability of repetition is low, which simplifies this part of the process.

Finally, when performing the data load using a command system, make sure that the set configurations work when executing:

php artisan migrate:fresh --seed

With this, you ensure that categories and posts are created with automated slugs, improving the structure and organization of your application significantly.

Contributions 2

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

隆Hola!, para convertir el t铆tulo/nombre a slug, he utilizado una librer铆a que ya viene con symfony, AsciiSlugger(), os dejo un ejemplo de como utilizarla:

use Symfony\Component\String\Slugger\AsciiSlugger;

protected function getDefaults(): array
{
    
    $slugger = new AsciiSlugger();
    $title = self::faker()->unique()->sentence();
    return [
        'category' => CategoryFactory::new(),
        'content' => self::faker()->text(),
        'slug' => strtolower($slugger->slug($title)),
        'title' => $title,
    ];
}

Hola a tod@s los que han llegado a esta parte del curso.

a partir de la version 3.2.1 de EasyAdmin, el metodo descrito en esta parte del curso, no funciona como el profe Italo dicta, pero por suerte, la documentacion de Symfony no nos deja tirados.

Asi que bueno, para convertir el slug en funcion del titulo, agreguen al inicio como es usual

use EasyCorp\Bundle\EasyAdminBundle\Field\SlugField

y pueden seguir llamando la clase de esta forma

SlugField::new('...')->setTargetFieldName('title');

Espero que haya sido de ayuda y recuerden: Nunca paren de aprender