简体   繁体   中英

Field 'activation_token' doesn't have a default value

I use laravel/passport for authentication in laravel. passport has column activation_token that should be a random string. when I register in application, I get this error:

Illuminate \\ Database \\ QueryException (HY000) SQLSTATE[HY000]: General error: 1364 Field 'activation_token' doesn't have a default value (SQL: insert into users ( name , email , password , updated_at , created_at ) values (Alireza, armazochi@gmail.com, $2y$10$gy2g4uQJPlX/1HneLEDei.b/BSHrv5B302ifQHPN0G6wbvYnjOiau, 2019-07-13 07:36:18, 2019-07-13 07:36:18))

In AuthController.php, I define value of name,password,email and activation_token. field name,email,password correctly save in database but activation_token dose not send to sql query and error creted:

SQLSTATE[HY000]: General error: 1364 Field 'activation_token' doesn't have a default value (SQL: insert into users ( name , email , password , updated_at , created_at ) values (Alireza, armazochi@gmail.com, $2y$10$gy2g4uQJPlX/1HneLEDei.b/BSHrv5B302ifQHPN0G6wbvYnjOiau, 2019-07-13 07:36:18, 2019-07-13 07:36:18))

I changed column activation_token to $table->string('activation_token')->default(null)->nullable(); and it worked,that show error relate to this part. why activation_token does not get random value?

User.php:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Laravel\Passport\HasApiTokens;


class User extends Authenticatable
{
    use Notifiable;
    use SoftDeletes;
    use HasApiTokens;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'active', 'activation_token',
    ];

    protected $dates = ['deleted_at'];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token', //'activation_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

2014_10_12_000000_create_users_table.php:

 <?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Str;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('activation_token');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->boolean('active')->default(false);
            $table->rememberToken();
            $table->timestamps();

            $table->softDeletes();
        });
    }



    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

AuthController.php:

<?php

namespace App\Http\Controllers;

use App\Notifications\SignupActivate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use App\User;
use Illuminate\Support\Str;


class AuthController extends Controller
{
    /**
     * Create user
     *
     *
    @param  [string] name
     *
    @param  [string] email
     *
    @param  [string] password
     *
    @param  [string] password_confirmation
     *
    @return [string] message
     */
    public function signup(Request $request)
    {
        $request->validate([
            'name' => 'required|string',
            'email' => 'required|string|email|unique:users',
            'password' => 'required|string|confirmed'
        ]);
        $user = new User([
            'name' => $request->name,
            'activation_token' => Str::random(60),
            'email' => $request->email,
            'password' => bcrypt($request->password),
        ]);
        $user->save();
        $user->notify(new SignupActivate($user));

        return response()->json([
            'message' => 'Successfully created user!'
        ], 201);
    }

    /**
     * Login user and create token
     *
     *
    @param  [string] email
     *
    @param  [string] password
     *
    @param  [boolean] remember_me
     *
    @return [string] access_token
     *
    @return [string] token_type
     *
    @return [string] expires_at
     */
    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|string|email',
            'password' => 'required|string',
            'remember_me' => 'boolean'
        ]);
        $credentials = request(['email', 'password']);
        $credentials['active'] = 1;
        $credentials['deleted_at'] = null;
        if(!Auth::attempt($credentials))
            return response()->json([
                'message' => 'Unauthorized'
            ], 401);
        $user = $request->user();
        $tokenResult = $user->createToken('Personal Access Token');
        $token = $tokenResult->token;
        if ($request->remember_me)
            $token->expires_at = Carbon::now()->addWeeks(1);
        $token->save();
        return response()->json([
            'access_token' => $tokenResult->accessToken,
            'token_type' => 'Bearer',
            'expires_at' => Carbon::parse(
                $tokenResult->token->expires_at
            )->toDateTimeString()
        ]);
    }

    /**
     * Logout user (Revoke the token)
     *
     *
    @return [string] message
     */
    public function logout(Request $request)
    {
        $request->user()->token()->revoke();
        return response()->json([
            'message' => 'Successfully logged out'
        ]);
    }

    /**
     * Get the authenticated User
     *
     *
    @return [json] user object
     */
    public function user(Request $request)
    {
        return response()->json($request->user());
    }


    public function signupActivate($token)
    {
        $user = User::where('activation_token', $token)->first();
        if (!$user) {
            return response()->json([
                'message' => 'This activation token is invalid.'
            ], 404);
        }
        $user->active = true;
        $user->activation_token = '';
        $user->save();
        return $user;
    }

}

This is a MySQL error because your database field does not have a default value set, and you did not pass a value for that property.

You could set a default value, such as NULL in your table schema settings.

Or, you could disable MySQL strict mode in Laravel.

/config/database.php

'mysql' => [
    ...
    'strict' => false,
    ...
],

In your migration you can do this to make the column nullable:

$table->string('activation_token')->nullable($value = true); 

Allows (by default) NULL values to be inserted into the column

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM