Screenshot of the error page
How do i go about this please? I created another table in my db where i generate OTPs and send to the users. in my table i made user_id and id(primary) but due to the nature of my code and how i want the site to function, i set user_id as a reference of id so that whenever OTP is generated, it will be the current user's ID
It seems there's no default value for user_id so i did ;
UserOTP::create(["user_id"=> auth()->id()]);
but its not working, what is wrong with my code please?
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUserOtpsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('user_otps', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->integer('code');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('user_otps');
}
}
This is the db migration file
CodePudding user response:
It's because you haven't set user_id field in $fillable property. Hence, Laravel ignored provided value for this field when you are using create() method.
However, before using the create method, you will need to specify either a fillable or guarded property on your model class. These properties are required because all Eloquent models are protected against mass assignment vulnerabilities by default.
Related document
protected $fillable = ['code' , 'user_id'];
CodePudding user response:
It's a SQL error not a PHP one. You're trying to insert a new row without a user_id but there's no default value set for that column, so it doesn't know what to set it as.
In your migration class, try giving it a default value:
$table->unsignedBigInteger('user_id')->default(null);
In any case, it also seems like you're not inserting with a user_id, only code, so you need to probably ensure that field can be persisted.
Edit: Yes, now you've posted your model, the problem is you haven't allowed the user_id field to be fillable:
// UserOtp.php
protected $fillable = ['code' , 'user_id'];
CodePudding user response:
Okay so i found it. Instead of keeping the answer to myself, i wanna share to whoever that may have this issue in the future.
so i made a function called rules where i forgot to add user_opts to code .
public function rules()
{
return [
'otpcode' => ['required','numeric',Rule::exists('user_otps','code')->where(function($query){
$query->whereUserId(auth()->id());
})]
];
adding user_otps to code actually solved it and everything is working now. The main problem wasnt this but rather, as the previous answers were saying. My user_id field wasnt receiving a value on submit.
Happy to resolve this issue and thanks to whoever helped

