What is Signed URL and How and When to Use It in Laravel
Hello Artisan,
In this Laravel signed URL example, I will show you what is Laravel signed URL is and how and when to use it? You know that Laravel gives us many prebuild features that help us to develop web applications very easily.
Let assume we want to create an invite-only registration link or a subscription link with a discount for a while. In this type of situation, we can use Laravel signed route URL to handle this condition. Because Laravel signed URL routes allow us to create routes accessible only when a signature is passed as a GET parameter.
signed route url
Have a look at the above route. See, this signed URL gives us two things, one is expires
and the other is the signature
. So without that signature, you can not access this route. The above URL only works within the expiration time and if you provide a valid signature.
Let's see how to create and use signed route URL in Laravel:
Step 1: Create Route
In this step, we will create a route to test our Laravel signed route URL. To create it update your web.php file.
routes/web.php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\TestController;
Route::get('/discount', [TestController::class,'index'])
->name('discount')
->middleware('signed');
Route::get('/generate-signature', [TestController::class,'discount']);
Have a look at the above route, with the middleware('signed')
method, we specify that this is a signed route.
Step 2: Create Controller
So in this step, if you want to create how to use signed URLs in Laravel, We need to create the below method to test the signed URL route in Laravel.
App\Http\Controllers\TestController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\URL;
class TestController extends Controller
{
public function index()
{
return 'some_code_goes_here';
}
public function discount()
{
return URL::temporarySignedRoute(
'discount', now()->addMinutes(30)
);
}
}
Now if you visit the following URL http://127.0.0.1:8000/generate-signature
, then you will see that our Laravel signed URL is working it will give you the below out.
http://127.0.0.1:8000/discount?expires=1636142920&signature=3ce33cabeec51572f982690a05cbc5c2aa2922eb015a6256319be5d78b3b92c0
Read also: How to Get Gravatar URL in Laravel Without Packages
Hope now you have understood that what is signed route URL is and how and when to use it in the Laravel application.