首页 > 解决方案 > Laravel - SQLSTATE [2300]:完整性违规约束 - 数据库上的电子邮件不能为空错误

问题描述

我收到了这个错误

SQLSTATE [23000]:完整性约束违规:1048 列“电子邮件”不能为空(SQL:插入invitesemail、、、、)值(? token, JW5UCmfAhuPGVKMM,2020-08-02 01:26:35,2020-08-02 01 :26:35))updated_atcreated_at

在我的 laravel 用户邀请应用程序中。这是我的邀请控制器

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use App\Invite;
use App\Mail\InviteCreated;
use Illuminate\Support\Facades\Mail;


class InviteController extends Controller
{
    
    public function invite() {
        return view ('invite');

    }
    
    public function process(Request $request) {
        do {
            $var = str_random(32);
    $token = str_random();
    
    } while (Invite::where('token', $token)->first());

    Invite::create([
        'email'=>$request->get('email'), 
        'token'=>$token]);
        
        Mail::to($request->get('email'))->send(new InviteCreated($invite));

        return redirect()->back;
}
    
    public function accept($token){
        if(!$invite = Invite::where('token', $token)->first()){
            abort(404);
        
        }
        User::create(['email'=>$invite->email]);

        $invite->delete();
        return "Good job! Invite accepted";
    }
}

迁移

public function up()
    {
        Schema::create('invites', function (Blueprint $table) {
            $table->increments('id');
            $table->string('email');
            $table->string('token', 16)->unique;
            $table->timestamps();
        });
    }

路线

Route::get('/', function () {
    return view('welcome');
});

Route::get('invite', 'InviteController@invite')->name('invite');
Route::get('invite', 'InviteController@process')->name('process');
Route::get('accept/{token}', 'InviteController@accept')->name('accept');

请问我在这里做错了什么?

标签: phplaravel

解决方案


您可以在数据库迁移中使电子邮件归档为空或放置

protected guarded = [] ; //inside the model

因为您正在使用 mass assignment ,所以当您使用 guarded off 时要小心,您需要运行表单验证。参考 laravel 文档 https://laravel.com/docs/7.x/eloquent#mass-assignment


推荐阅读