Prevent multiple slugs from being the same

default discord avatar
Plain134
10 months ago
6

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
    noheadphones
    10 months 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
    Plain134
    10 months ago

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



    thanks a lot

  • default discord avatar
    noheadphones
    10 months ago

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

  • default discord avatar
    Plain134
    10 months ago

    It works perfectly too, so thank you!

Open the post
Continue the discussion in Discord
Like what we're doing?
Star us on GitHub!

Star

Connect with the Payload Community on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.