Laravel security questions helps you easily integration security question facility for your project
composer require bluecloud/laravel-security-question
Run the following command to create tables to enable saving security questions
php artisan migrate
The package allows you to publish a config file to change settings for the package. Run the command below and
select Bluecloud\SecurityQuestionHelpers\SecurityQuestionHelpersProvider
. A configuration file will be created
at config/questions.php
php artisan vendor:publish
Run the following command
php artisan questions:migrate
Add the HasSecurityQuestions
trait to your App\Models\User
model as indicated below.
use Bluecloud\SecurityQuestionHelpers\HasSecurityQuestions;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable, HasSecurityQuestions;
}
To add question(s) for a user, add the code below
$user = auth()->user();
$user->save_questions([
["security_question_id" => 1, "answer" => "Blantyre, Malawi"]
]);
To check a user's submitted answer against the saved answers, add the code below
$question = SecurityQuestion::find(1);
$check = $user->check_answer($question, "Blantyre, Malawi");
Note: The questions will sync. If the question was already attached for the user, the new answer will update the existing record
To manage question, you can make use of preconfigured api endpoints
GET /security-questions
POST /security-questions
{
"name": "Sample security question"
}
DELETE /security-question/{id}
Change package settings
Navigate to config/questions.php
and find default security questions. You may change if you please.
<?php
return [
"seeds": []
]
By default, the package turns strict mode
off. When strict mode is off, the package ignores case for the answers
and removes all whitespaces and special characters to ease the matching of user submitted answers. If you want the
answers to match exact case and whitespace, turn strict mode
on in config/questions.php
'strict' => true,
To protect /security-questions
routes, and middleware in config/questions.php
. For example to
add auth:sanctum
for authentication:
'middleware' => ["auth:sanctum"]
To change the base routes path for /security-questions
for example in config/questions.php
change the
following line
'path' => 'api/questions',
Laravel Sanctum is open-sourced software licensed under the MIT license.