dounuogong0358 2019-07-13 07:59
浏览 166

字段'activation_token'没有默认值

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;
    }

}
  • 写回答

2条回答 默认 最新

  • doqs8936 2019-07-13 08:32
    关注

    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,
        ...
    ],
    
    
    评论

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示