Henry Adepegba
Henry Adepegba

Reputation: 1

Laravel - SQLSTATE[2300]: Integrity violation constraint - Email cannot be null error on database

I got this error

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'email' cannot be null (SQL: insert into invites (email, token, updated_at, created_at) values (?, JW5UCmfAhuPGVKMM, 2020-08-02 01:26:35, 2020-08-02 01:26:35))

in my laravel users-invite app. This is my InviteController

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

Migrations

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

Routes

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');

Please what am i getting wrong here?

Upvotes: 0

Views: 320

Answers (1)

Leong
Leong

Reputation: 139

you can make email filed nullable in database migration or put

protected guarded = [] ; //inside the model

because you are using mass assignment , beware when you using guarded off , you need to run a form validation. refer to laravel doc https://laravel.com/docs/7.x/eloquent#mass-assignment

Upvotes: 0

Related Questions