Hello all,
I tried many ways to unpublish a document but seems it not work.
I update a document with the body
http://localhost:1337/api/apps/[:documentId]
{
“data”: {
“publishedAt”: null
}
}
Could you please support to point out which is the correct way to unpublish a document?
ps: I’m using strapi 5 and already enabled draft & published
Thank you so much!
You can handle this by customizing the controller for your content type. I had a similar use case where I needed to unpublish an entry when publishedAt: null
was sent in a PUT request. Here’s how I solved it:
In the controller for my content type (e.g., category
), I extended the update
action to check if publishAt
is null
. If it is, I set the publishedAt
field to null
, effectively unpublishing the entry. This is similar to what Strapi does internally when you unpublish something manually.
async update(ctx) {
const {id} = ctx.params;
const {publishedAt} = ctx.request.body.data;
if (publishedAt === null) {
await strapi
.documents('api::category.category')
.unpublish({ documentId : id, locale: '*' });
return await strapi.documents('api::category.category').findOne({
documentId: id,
status: 'draft'
});
}
return await super.update(ctx);
}
}));```
1 Like
In Strapi 5.12.4 I got it work with this code:
module.exports = createCoreController('api::paper.paper', ({ strapi }) => ({
async update(ctx) {
//console.log('update paper controller, ctx.params:', ctx.params, 'ctx.request.body:', ctx.request?.body);
const { id } = ctx.params;
const { publishedAt } = ctx.request.body.data;
const res = await super.update(ctx);
if (publishedAt === null) {
console.log('Unpublishing document triggered by publishedAt:null', id);
await strapi
.documents('api::paper.paper')
.unpublish({ documentId: id, locale: '*' });
/*return await strapi.documents('api::paper.paper').findOne({
documentId: id,
status: 'draft'
});*/
}
return res;
}
}));
If I do return await super.update(ctx);
then .unpublish method will trigger this error:
Error: Undefined binding(s) detected when compiling WHERE. Undefined column(s): [t0.id] query: where
t0.
id = ?
Also unpublishing the document before the actual update misses the whole point as with an update it gets published again.