How to generate and validate token manually in laravel?

by herminia_bruen , in category: PHP Frameworks , 5 months ago

How to generate and validate token manually in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by brandy , 5 months ago

@herminia_bruen 

To manually generate and validate tokens in Laravel, you can use the Str facade to generate a random string as the token and the Hash facade to hash the token before storing it in the database. Here is an example of how you can generate and validate tokens manually:

Generating a token:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
use IlluminateSupportStr;

// Generate a random token
$token = Str::random(60);

// Hash the token before storing it in the database
$hashedToken = Hash::make($token);

// Store the hashed token in the database
// Example: $user->api_token = $hashedToken;


Validating a token:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
use IlluminateSupportFacadesHash;

// Retrieve the hashed token from the database
// Example: $hashedToken = $user->api_token;

// Check if the token is valid
if (Hash::check($token, $hashedToken)) {
    // Token is valid
    // Proceed with authentication logic
} else {
    // Token is invalid
    // Handle invalid token scenario
}


By following these steps, you can manually generate and validate tokens in Laravel. Remember to adjust the code according to your specific application requirements and database structure.