php - Laravel - SQLSTATE [2300]:完整性违规约束 - 数据库上的电子邮件不能为空错误
问题描述
我收到了这个错误
SQLSTATE [23000]:完整性约束违规:1048 列“电子邮件”不能为空(SQL:插入
invites
(token
, JW5UCmfAhuPGVKMM,2020-08-02 01:26:35,2020-08-02 01 :26:35))updated_at
created_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');
请问我在这里做错了什么?
解决方案
您可以在数据库迁移中使电子邮件归档为空或放置
protected guarded = [] ; //inside the model
因为您正在使用 mass assignment ,所以当您使用 guarded off 时要小心,您需要运行表单验证。参考 laravel 文档 https://laravel.com/docs/7.x/eloquent#mass-assignment
推荐阅读
- arrays - 从存储在 SQL Server 列中的复杂对象中删除 JSON 属性
- idp - 具有 B2B 注册流程的第 3 方 IDP
- ios - iOS 的 AUv3 MIDI 插件中的时间戳
- python - Scatter palindrome - 如何通过字典解析以找出形成回文的子串组合
- node.js - Jest - 在另一个模块函数中模拟函数
- java - Excel中的Outputdata在SpringBoot中无法正确迭代
- amazon-web-services - 无法使用 EKS 上的 EMR 在 EMR Studio Notebook 中加载内核
- java - 缺少返回语句是什么意思?
- nrules - 有没有人有动态 NRules 的工作示例?
- java - 当我尝试实例化 JobOperator 时,抛出了 ClassNotFoundException。(org.apache.commons.dbcp2.BasicDataSource)