Home > OS >  Saving Model in Laravel does not work - SQL Error column has no default value
Saving Model in Laravel does not work - SQL Error column has no default value

Time:03-22

I'm trying to save a Model to my database. But for some reason it does not work. This is the error I get:

SQLSTATE[HY000]: General error: 1364 Field 'token' doesn't have a default value (SQL: insert into `user_registration_tokens` (`updated_at`, `created_at`) values (2022-03-21 17:40:13, 2022-03-21 17:40:13))

But when I dump my model I can see that the values have been set. But I can't find token and user_id in the sql query inside the error message.

My model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;

/**
 * @property string $token;
 *
 * @property int $user_id;
 */
class UserRegistrationToken extends BaseModel
{
    use HasFactory;

    public string $token;

    public int $user_id;
}

How I'm trying to save the model:

$registrationToken = new UserRegistrationToken;

$registrationToken->user_id = $userId;
$registrationToken->token = '$token';

$registrationToken->save();

NOTE: When trying to save the item trough mass assignment it works. For security reasons I don't want this.

CodePudding user response:

Try to set a $fillable to your model!

Remove public string $token; and public int $user_id;

Also you may set token and user_id nullable in your db structure.

protected $fillable=['token','user_id'];

Then you may use it in your controller like this(Or like what you’ve done before):

UserRegistrationToken::create([

'token'=>$token,
'user_id'=>$userId

]);

CodePudding user response:

In your model You need to say which fields are fillable.

<?php

namespace App\Models;

 use Illuminate\Database\Eloquent\Factories\HasFactory;

/**
 * @property string $token;
 *
 * @property int $user_id;
*/
class UserRegistrationToken extends BaseModel
{
    use HasFactory;
    
   protected $fillable = [
        'token',
       'user_id',  
     ];

Then :

$token  = ['token'=>$token, 'user_id'=>$userId];
UserRegistrationToken::create($token);

CodePudding user response:

Change the annotation to allow null values:

/**
 * @property string|null $token;
 *
 * @property int $user_id;
 */

And also the property type:

public ?string $token;
  • Related