Is there a way to validate the preview link token in code?

Hi,

I was wondering if there is a way to validate the preview token yourself? I use subpages as blocks and want to show the draft blocks when you are previewing from the panel. At this moment I loop through the listed ones so I would like to loop through listed and drafts and if the preview token is there AND if I would be able to check that it’s valid I could show the draft blocks too.

Cheers!

Sam

The preview token is created for each page individually, so I wonder what preview token you would want to validate…

I think it would probably make more sense to show the drafts in your template bases on whether or not a user is logged in?

That’s indeed a way to do it. Haven’t thought of that yet. Downside is that if you are logged in the site you will always see those blocks and not only when you are going via the preview.

To clarify my question, yes, the token is per page and I have a parent page wich includes subpages as “blocks”. So if the token of the parent would check out I could include the draft children also.

foreach($page->children()->listed()->filterBy('intendedTemplate', 'not in', option('blocks.first')) as $block)
{
   snippet('blocks/'. $block->intendedTemplate(), compact('block'));
}

The problem is how do you know you are going via the preview? Because unless the page is a draft, there is no token or special url, unless you specifically define one.

You go via the preview of the block that is in draft, it will add the token and still go to the parent page if you change the preview option.

preview: "{{ page.parent.url }}/#{{ page.slug }}"

results in:

/page/?token=a6f15ad4804348af98ae1ad8a4335357bc33b391#sdf

But I’m guessing the answer to my question is that you can’t “validate” the token in a controller or what not? :sweat_smile:

Yes, but only then. I thought you wanted to preview the parent page.

You can check if the current URL is the preview URL of the block and show a block based on that, but then this would only be true for that particular block, not all draft blocks.

If you actually want to see all draft blocks, you could create a special preview url for the parent page (maybe with a query string preview and then check if the current url contains that query and if it the same as the previewUrl().

1 Like

Allright, I can work with this previewUrl, did a little test and I can validate the token with it, awesome.

Even if very unlikely if other people ever would like to get he token, here’s a small test to retrieve it:

$q = [];
parse_str(parse_url($pages->drafts()->first()->previewUrl(), PHP_URL_QUERY), $q);
dump($q);
die();

Tx @texnixe :relaxed: