Home > Software engineering >  Is there a one time link generation Laravel?
Is there a one time link generation Laravel?

Time:06-06

Is it possible to create a one time link in Laravel? Once you open the link it expires?

I have created a Temporary Signed Link, but I can open it multiple times. How do I counter it?

CodePudding user response:

There is this package that can help you

https://github.com/linkeys-app/signed-url/

This will generate a link valid for 24hours and for just one click .

$link = \Linkeys\UrlSigner\Facade\UrlSigner::generate('https://www.example.com/invitation', ['foo' => 'bar'], ' 24 hours', 1);

The first time the link is clicked, the route will work like normal. The second time, since the link only has a single click, an exception will be thrown. Of course, passing null instead of ' 24 hours' to the expiry parameter will create links of an indefinite lifetime.

CodePudding user response:

There maybe a package that provides a functionality like this... always worth looking on Packagelist before building something rather generic like this from scratch. But, it's also not a hard one to build from scratch.

First you'll need database persistence, so create a model and a migration called UniqueLink. In the migration you should include a string field called "slug", a string field called path, and a timestamp field called "used_at."

Next create a controller with a single __invoke(string $slug) method. In the method look up the $link = UniqueLink::where('slug', $slug)->first(); Update the models' used_at parameter like so $link->update(['used_at' => Carbon::now()]);

Then return a redirect()->to($link->path);

Add a route to your routes file like this Route::get('/unique-link/{slug}', UniqueLinkController::class);

Now you'll just need to create a method to add these links to the db which create a slug (you could use a UUID from Str::uuid() or come up with something more custom) and a path that the link should take someone. Over all a pretty straight forward functionality.

CodePudding user response:

You could track when the URL is visited at least once and mark it as such for the user if you really want to, or you could reduce the expiry down to a few mins.

URL::temporarySignedRoute( 'foobar', now()->addMinutes(2), ['user' => 100] );
  • Related