Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

Prevent multiple slugs from being the same

default discord avatar
plainnn2 years ago
4

Hi guys, i'm currently working on building a blog using payload. I've just implemented a hook for formatting the title and setting it as a slug like so



export const formatSlug: FieldHook = async ({ value, data }) => {
  return data?.title?.replace(/ /g, '-').toLowerCase() ?? value
}


    {
      name: 'slug',
      type: 'text',
      hooks: {
        beforeChange: [formatSlug],
      },
      label: 'The slug is automatically generated from the title.',
      admin: {
        readOnly: true,
      },
    },


But this has the potential to create two slugs the same (if for whatever reason the title of the blog post is repeated) - Is there anyway to prevent his happening?

  • default discord avatar
    paulpopus2 years ago

    you can set "unique: true" on the field



    I believe that should cover it to make sure that your slug is actually unique but i think it may be per collection and not global, not sure about that part

  • default discord avatar
    plainnn2 years ago

    🤦‍♂️ didn't realise it was that simple



    thanks a lot

  • default discord avatar
    paulpopus2 years ago

    Dw about it, theres lots of random small bits like this thats not easy to always find

  • default discord avatar
    plainnn2 years ago

    It works perfectly too, so thank you!

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get dedicated engineering support directly from the Payload team.