Hello, you can check the API documentation for Laravel.
https://laravel.com/docs/5.8/api-authentication
Your users table should have this field for the api_token:
$table->string('api_token', 80)->after('password')
->unique()
->nullable()
->default(null);
Migrate the table
php artisan:migrate
You can make a random api token with this attribute when creating the user:
'api_token' => Str::random(60),
And dont forget to add:
use Illuminate\Support\Facades\Hash;
at the top of the controller.
If you want your token to be hashed you need to change the config/auth.php file like this:
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => true,
],
You need to make a controller for generating the api_tokens and inserting them into the db.
class ApiTokenController extends Controller
{
/**
* Update the authenticated user's API token.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function update(Request $request)
{
$token = Str::random(60);
$request->user()->forceFill([
'api_token' => hash('sha256', $token),
])->save();
return ['token' => $token];
}
}
In this file you can create, update, refresh, etc. the token. As you can see the update method here is for 'user()', but it can be for whatever you want, like 'customers'.
In your routes/api.php add this:
use Illuminate\Http\Request;
Route::middleware('auth:api')->get('/user', function(Request $request) {
return $request->user();
})
And thats it. Check out how you can pass tokens in request here:
https://laravel.com/docs/5.8/api-authentication#passing-tokens-in-requests
This is for laravel 5.8 version. Hope this helps.
Regards. Daniel
sangrialdrete, manojibcarockers liked this reply
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community