[英]SQLSTATE[HY000]: General error: 1364 Field 'photo' doesn't have a default value in laravel 5.5
[英]I keep getting this error: Field 'api_token' doesn't have a default value in PHP Laravel 5.5
我是laravel的新手。 我正在嘗試制作一個api。 因此,如果您注冊為(auth)用戶,將獲得一個api_token以便您可以訪問儀表板。這是我的一些代碼。 當我嘗試注冊時,出現此錯誤:
Illuminate \\ Database \\ QueryException(HY000)SQLSTATE [HY000]:常規錯誤:1364字段“ api_token”沒有默認值(SQL:插入users
( name
, email
, password
, updated_at
, created_at
))值(goddies,f @ gmail.com,$ 2y $ 10 $ uKJPI9hBJSdygMf7MefP1eM1GQ7VM3s74eVy5qcuFj4 / s8HH2Iun。,2017-11-13 19:11:38,2017-11-13 19:11:38)
在為用戶遷移時:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->string('api_token', 20)->unique();
$table->rememberToken();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('users');
}
}
這是我的用戶模型:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'password', 'api_token',
];
protected $hidden = [
'password', 'remember_token', 'api_token',
];
}
該錯誤表明在創建新記錄時api_token
字段為空。 這就是為什么錯誤會顯示“它沒有默認值”的原因。
在UserController
修改store
方法(或用於保存新記錄的store
方法),並為api_token
字段生成一個值:
public function store(Request $request)
{
// some validation logic
$user = new User;
$user->name = $request->name;
$user->email = $request->email;
$user->password = $request->password;
// ... the rest of your fields
// to generate a new token for the new user
$user->api_token = str_random(20);
// then save
$user->save();
return $user;
}
如果您使用工廠/播種機,則需要生成該字段或使數據庫中的該列可為空。
該錯誤表明在創建新記錄時api_token
字段為空或未設置為NULL
。 這就是為什么該錯誤表明它沒有默認值的原因
因此您可以簡單地修改用戶表中的列,並將default
值設置為NULL
並插入新記錄。
如果您想避免發生此錯誤,則需要將列“ api_token”設置為可空值,以便在您的請求“ api_token”沒有值的情況下將其默認值設置為“ NULL”,
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->string('api_token', 20)->unique()->nulllable();
$table->rememberToken();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('users');
}
希望這可以幫助 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.