I am playing around with Laravel Authentication.
On a freshly created Laravel app with Composer, I followed literally the instructions until this point (included)
https://laravel.com/docs/5.8/api-authentication#generating-tokens
When I register a new user, however, the api_token field is NULL.
What else do I need to do in order to start generating the api token when a user registers??
Create method in RegisterController:
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'api_token' => Str::random(60),
]);
}
Migration (I called it Token) updating the users table:
class Token extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('api_token', 80)->after('password')
->unique()
->nullable()
->default(null);
});
}
App\User model:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
In your user model add 'api_token' to your fillables
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
'api_token'
];
After creating migration , run the migrate Artisan command:
php artisan migrate
If you are using the Homestead virtual machine, you should run this command from within your virtual machine:
php artisan migrate --force
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With