How to replace the Strapi ID field with a slug field

  Рет қаралды 11,450

Strapi

Strapi

Күн бұрын

In this video, we discuss how you can replace the Strapi findOne controller action to accept a slug instead of an id. This allows your url path slug to dictate which content is returned from Strapi and is useful when creating blogs with Strapi. This allows you to have user-friendly urls instead of having id’s in the url.
Chapters:
0:00:09 - Setting up a POST in the CMS
0:01:19 - Overriding the findOne Route
0:02:55 - Overriding the findOne Controller
0:05:45 - Testing Our Slug
Learn more with Brayden Girard - / braydengirard
---
Get started with Strapi: strapi.io/
Try live demo: strapi.io/demo
Strapi Blog: strapi.io/blog
Find help in our Forum: forum.strapi.io/
We are hiring! strapi.io/careers

Пікірлер: 46
@patra0o
@patra0o 2 жыл бұрын
This is brilliant mate! Kindly create a video on how to add a custom wrote instead of overwriting it. I want to search for a content type by it's ID and slug at the same time.
@rahmanare2582
@rahmanare2582 2 жыл бұрын
Thank You, But i cant access any dynamic fields on single post, even when i use ?populate=* . Is there a fix
@adolforamirezdesancristoba3745
@adolforamirezdesancristoba3745 Жыл бұрын
Thank you so much, I was completely lost on this.
@kima111
@kima111 2 жыл бұрын
Thank you for the video! It looks like however that the override broke the relationships, and am unable to use populate to query related fields. Is there a fix to that?
@CodingAfterThirty
@CodingAfterThirty 2 жыл бұрын
here is another way to do this to include the ability to pass populate in your query forum.strapi.io/t/strapi-v4-search-by-slug-instead-id/13469/21?u=paul_brats
@arjunhadke1113
@arjunhadke1113 2 жыл бұрын
This was very helpful. I came to this video with some Googling which first led me to the Strapi Forum where someone had linked to this video. Thanks for the amazing product. I am guessing Strapi will be a great help for some of the use cases at work.
@24worldde84
@24worldde84 2 жыл бұрын
Your `routes/custom.js` must locate before your file(ex: post.js). `custom.js` and `new(post).js`. If your `custom.js` locate after `post.js`, it doesn't work. So I changed `0post.js` like that
@soymohsen
@soymohsen Жыл бұрын
wow!! I couldn't figure it after trying for 1 hour! You saved me! Thanks man
@ShahriarKh
@ShahriarKh Жыл бұрын
Life saver!
@mohamedihebhichri9862
@mohamedihebhichri9862 Жыл бұрын
thank you bro you really save my day
@MQadri83
@MQadri83 11 ай бұрын
You response is still helping! 🤩, I found it weird that you didnt need to specify the route somewhere, it just chooses the first file in folder alphabetically!
@oasiswow1818
@oasiswow1818 2 жыл бұрын
Thanks! I also want to know how to use populate when I change id to slug
@DarokViana
@DarokViana 2 жыл бұрын
Unfortunately, by doing this customization, API calls to the changed endpoint no longer populate nested fields like images and components.
@hexam1ne703
@hexam1ne703 2 жыл бұрын
stop using it. I'd rather host it on WordPress.
@mattie_world
@mattie_world 2 жыл бұрын
did you get around this? I can't believe I'm having this issue!
@hanes2
@hanes2 2 жыл бұрын
Can we make one that doesn’t override ? In the past I’ve always had two functions… id finds slug, and slug find id
@webstudiochamper5058
@webstudiochamper5058 Жыл бұрын
Thank you for video! Any ideas how it can be used with GraphQL?
@ilirbajrami2902
@ilirbajrami2902 Жыл бұрын
Did you find out? It's not working on my GraphQL
@webstudiochamper5058
@webstudiochamper5058 Жыл бұрын
@@ilirbajrami2902 I think the only way to make it possible (i mean getting item by it's slug) on GraphQL is by using filter. Example: products: ( filters: { slug: { eq: $slug } } )
@ilirbajrami2902
@ilirbajrami2902 Жыл бұрын
@@webstudiochamper5058 thanks for the reply! so in this case we dont need the customization from the video, i assume. Is there any downside using filter?
@webstudiochamper5058
@webstudiochamper5058 Жыл бұрын
@@ilirbajrami2902 yes, filter isn't required any customization. I think filtering results can be little bit lower. You can do a several tests to check it.
@ilirbajrami2902
@ilirbajrami2902 Жыл бұрын
What do you mean "lower"? Or you mean slower?
@voloshyn_o
@voloshyn_o 2 жыл бұрын
I don't know why, but I can't found slug from params. If I use like this where: { slug: id } it's work
@georgepustovit8728
@georgepustovit8728 9 ай бұрын
In case someone struggles with the population and everything, I came up with another, much simpler solution. Instead of rewriting a fucking controller, you can filter the request to the parent route by the slug so it will return just a single element. This way you can populate fields as in any other request. Hope it helps someone. export async function getSingleBlog(slug) { const url = new URL('/api/blogs'); url.search = qs.stringify({ filters: { slug, }, populate: { cover: { fields: ['url', 'alternativeText', 'width', 'height'], }, category: { fields: ['otherFieldsYouMightNeed'], }, }, }); // logic for sending request goes here }
@_boza
@_boza Жыл бұрын
Thnx!
@mattie_world
@mattie_world 2 жыл бұрын
It works, but I can't populate nested fields!! Images, components, etc..
@mattie_world
@mattie_world 2 жыл бұрын
myurl.etc/api/endpoints/slug?populate=* does not populate everything. nor does /slug?populate=image which works on my other pages
@YoonTso
@YoonTso 2 ай бұрын
## In the routes folder, the order of the files is crucial. If the order is - article.ts - custom.ts the output of ctx.params is: { '0': 'api/articles/test', id: 'test' } If the order is - 0custom.ts - article.ts the output of ctx.params is: { '0': 'api/articles/test', slug: 'test' } ## Populate const entities = await strapi .service("api::article.article") .find({ filters: { slug }, populate: ctx.query.populate }); const updatedEntity = await strapi .service("api::article.article") .findOne(entity.documentId, { populate: ctx.query.populate, });
@thapamilan7
@thapamilan7 2 жыл бұрын
not working ? Any idea ?
@shamsfiroz
@shamsfiroz 2 жыл бұрын
replace this line then it works const entity = await strapi.db.query("api::article.article").findOne({ where: slug, });
@vladimircontreras
@vladimircontreras 2 жыл бұрын
Those with the population problem, you can "restore" it with the populate key when calling findOne(): populate: { sections: { populate: { fields: ['*'], } } } You can also retrieve from those parameters from the context 🙂
@mr.yellow3250
@mr.yellow3250 2 жыл бұрын
how man ?
@jackcohle
@jackcohle 2 жыл бұрын
@@mr.yellow3250 where: {slug: id}, populate: { name_populate: { populate: { name_populate: { populate: { fields: ['*'], } }, name_populate: { populate: { fields: ['*'], } }, name_populate: { populate: { fields: ['*'], } } } } } name_populate : You need to change these fields according to your own. You call what you need. I wanted to give multiple examples.
@VincentFulco
@VincentFulco 2 жыл бұрын
Would love to see this in a contiguous video since youtube doesn't link easily from vid to vid. Too easy to get interrupted in the flow.
@afxcrush41
@afxcrush41 Жыл бұрын
Not working (march 2023)
@faisalkkn8208
@faisalkkn8208 Жыл бұрын
async findOne(ctx) { const { id } = ctx.params; const entity = await strapi.db.query('api::blog.blog').findOne({ where: { slug: id }, }); const sanitizedEntity = await this.sanitizeOutput(entity); return this.transformResponse(sanitizedEntity) }
@richardroberts3546
@richardroberts3546 2 жыл бұрын
Lots of people seem to be having problems with 'populate' not working.. This is the solution const queryPopulate = (populate) => { if (Array.isArray(populate)) { return populate.flatMap(value => { return value.split(',').map(value => value); }) } } async findOne(ctx) { const { sku } = ctx.params; const { populate } = ctx.query const entity = await strapi.db.query('api::foo.foo').findOne({ where: { sku }, populate: queryPopulate(populate) }) }
@grapegirl
@grapegirl 11 ай бұрын
hi there. do you know how do you populate images in dynamic zones?
@kruemelfelix
@kruemelfelix Жыл бұрын
If you want to populate something you can change the query to this: ``` const entity = await strapi.db.query('api::partner.partner').findMany({ where: { partner_id }, populate: true }) ``` Change partner.partner and partner_id accordingly.
@christiandanielortizororbi122
@christiandanielortizororbi122 5 ай бұрын
You are a lifesaver, I owe you a drink 🍹
@IfechukwuObijiofor
@IfechukwuObijiofor Жыл бұрын
there's a red squigly lines on const sanitizedEntity = await this.sanitizeOutput(entity); return this.transformResponse(sanitizedEntity); Who else is having this problem in July 2023
@ankush9117
@ankush9117 Жыл бұрын
me
@johnbolanoscamacho6570
@johnbolanoscamacho6570 Жыл бұрын
async findOne(ctx) { const { slug } = ctx.params; const response = await strapi.db .query("api::product.product") .findOne({ where: { slug } }); return response; }
@johnbolanoscamacho6570
@johnbolanoscamacho6570 Жыл бұрын
Don't sanitize it.
@MrDragos696
@MrDragos696 11 ай бұрын
const sanitizedEntity = await this.sanitizeOutput(entity, ctx)
Updating Your Own User Info in Strapi
9:10
Strapi
Рет қаралды 7 М.
How is this Website so fast!?
13:39
Wes Bos
Рет қаралды 1,4 МЛН
Support each other🤝
00:31
ISSEI / いっせい
Рет қаралды 81 МЛН
Сестра обхитрила!
00:17
Victoria Portfolio
Рет қаралды 958 М.
How Strong Is Tape?
00:24
Stokes Twins
Рет қаралды 96 МЛН
How to host a Strapi project on Heroku in 2022 | A step by step guide
11:40
How to work with data in Astro
26:04
Coding in Public
Рет қаралды 26 М.
This is How I Scrape 99% of Sites
18:27
John Watson Rooney
Рет қаралды 266 М.
Why I Like Strapi
13:12
Chris Hawkes
Рет қаралды 33 М.
Making Websites With Next.js And Strapi - [06] - Dynamic Routes
19:51
Watch and Learn
Рет қаралды 17 М.
Strapi Cloudinary: upload provider configuration (Strapi v4)
9:39
Artcoded //by Jib
Рет қаралды 6 М.
13 Levels of Beatboxing: Easy to Complex | WIRED
16:38
WIRED
Рет қаралды 3 МЛН
Strapi v4 findOne by slug instead of id
5:00
sonam serchan
Рет қаралды 3,3 М.
Content-Types Builder 101
30:33
Strapi
Рет қаралды 18 М.
How to improve SEO using Strapi
5:48
Strapi
Рет қаралды 9 М.
Support each other🤝
00:31
ISSEI / いっせい
Рет қаралды 81 МЛН