laravel generate token code example
Example 1: laravel generate unique token
use Illuminate\Support\Str;
public function yourFunction(){
$var = Str::random(32);
dd($var);
}
Example 2: laravel get authorization bearer token
//get Authorization Bearer Token value
$token = $request->bearerToken();
Example 3: laravel 7 user registration using api post endpoint
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class AuthController extends Controller
{
public $loginAfterSignUp = true;
public function register(Request $request)
{
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => bcrypt($request->password),
]);
$token = auth()->login($user);
return $this->respondWithToken($token);
}
public function login(Request $request)
{
$credentials = $request->only(['email', 'password']);
if (!$token = auth()->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
public function getAuthUser(Request $request)
{
return response()->json(auth()->user());
}
public function logout()
{
auth()->logout();
return response()->json(['message'=>'Successfully logged out']);
}
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60
]);
}
}
Example 4: laravel token authentication
// add api_token to users table
Schema::table('users', function ($table) {
$table->string('api_token', 80)->after('password')
->unique()
->nullable()
->default(null);
});
// Create token for existing users, code can also be added to registerController
$token = Str::random(60);
$user = User::find(1);
$user->api_token = hash('sha256', $token); // <- This will be used in client access
$user->save();
//config/auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token', // <- Add this entry
'provider' => 'users',
'hash' => false,
],
],
//routes/api.php
// Add "middleware('auth:api')" as below
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
//client access example (in Vue js)
axios.get('http://example.com/api/user',
{
headers: {
'Accept': 'application/json',
'Authorization': 'Bearer '+ 'user-api-token'
}
}
)
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
Example 5: encrypt api token laravel
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCEOSTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('c_e_o_s', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('company_name');
$table->year('year');
$table->string('company_headquarters');
$table->string('what_company_does');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('c_e_o_s');
}
}