[php] General error: 1364 Field 'user_id' doesn't have a default value

I am trying to assign the user_id with the current user but it give me this error

SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a 
default value (SQL: insert into `posts` (`updated_at`, `created_at`) 
values (2017-04-27 10:29:59, 2017-04-27 10:29:59))

here is my method

//PostController
Post::create(request([
        'body' => request('body'),
        'title' => request('title'),
        'user_id' => auth()->id()
    ]));

with these fillables

//Post Model
protected $fillable = ['title', 'body', 'user_id']

However this method do the job

//PostController
auth()->user()->publish(new Post(request(['title' ,'body']))); 

//Post Model
public function publish(Post $post)
{
    $this->posts()->save($post);
}

any idea why this fail? enter image description here

This question is related to php laravel

The answer is


you need to change database strict mode. for disable follow below step

  1. Open config/database.php

  2. find 'strict' change the value true to false and try again


I've had a similar issue with User registration today and I was getting a

SQLSTATE[HY000]: General error: 1364 Field 'password' doesn't have a default value (SQL: insert into users

I fixed it by adding password to my protected $fillable array and it worked

protected $fillable = [
  'name',
  'email',
  'password',
];

I hope this helps.


Here's how I did it:

This is my PostsController

Post::create([

    'title' => request('title'),
    'body' => request('body'),
    'user_id' => auth()->id() 
]);

And this is my Post Model.

protected $fillable = ['title', 'body','user_id'];

And try refreshing the migration if its just on test instance

$ php artisan migrate:refresh

Note: migrate: refresh will delete all the previous posts, users


There are two solutions for this issue.

First, is to create fields with default values set in datatable. It could be empty string, which is fine for MySQL server running in strict mode.

Second, if you started to get this error just recently, after MySQL/MariaDB upgrade, like I did, and in case you already have large project with a lot to fix, all you need to do is to edit MySQL/MariaDB configuration file (for example /etc/my.cnf) and disable strict mode for tables:

[mysqld]
sql_mode=NO_ENGINE_SUBSTITUTION

This error started to happen quite recently, due to new strict mode enabled by default. Removing STRICT_TRANS_TABLES from sql_mode configuration key, makes it work as before.


Try using Auth::id(), like

Post::create([ 'body' => request('body'), 'title' => request('title'), 'user_id' => Auth::id()]);

also remember to include Auth facade at top of your controller which is App\Http\Controllers\Auth


Try

'user_id' => auth()->id
or

'user_id' => Auth::user()->id

instead of

'user_id' => auth()->id()

User Auth::user()->id instead.

Here is the correct way :

//PostController
Post::create(request([
    'body' => request('body'),
    'title' => request('title'),
    'user_id' => Auth::user()->id
]));

If your user is authenticated, Then Auth::user()->id will do the trick.


In my case, the error was because I had not declared the field in my $fillable array in the model. Well, it seems to be something basic, but for us who started with laravel it could work.


Use database column nullble() in Laravel. You can choose the default value or nullable value in database.


The above error can be as a result of wrongly named input variables from the view form, which resorts to seeking a default value since no variable is supplied hence-- SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into posts (updated_at, created_at) values (2017-04-27 10:29:59, 2017-04-27 10:29:59))


use print_r(Auth);

then see in which format you have user_id / id variable and use it


It's seems flaw's in your database structure. Keep default value None to your title and body column.

Try this:

$user_login_id = auth()->id();
Post::create(request([
        'body' => request('body'),
        'title' => request('title'),
        'user_id' => $user_login_id
    ]));

$table->date('user_id')->nullable();

In your file create_file, the null option must be enabled.


 Post::create([
      'title' => request('title'),
      'body' => request('body'),
      'user_id' => auth()->id()
    ]);

you dont need the request() as you doing that already pulling the value of body and title


Questions with php tag:

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop? Target class controller does not exist - Laravel 8 Message: Trying to access array offset on value of type null Array and string offset access syntax with curly braces is deprecated Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error How to fix "set SameSite cookie to none" warning? The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"? dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac What does double question mark (??) operator mean in PHP Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client php mysqli_connect: authentication method unknown to the client [caching_sha2_password] Converting a POSTMAN request to Curl Composer require runs out of memory. PHP Fatal error: Allowed memory size of 1610612736 bytes exhausted Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required Issue in installing php7.2-mcrypt Xampp localhost/dashboard How can I run specific migration in laravel How to change PHP version used by composer Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory Artisan migrate could not find driver phpMyAdmin ERROR: mysqli_real_connect(): (HY000/1045): Access denied for user 'pma'@'localhost' (using password: NO) Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) laravel 5.5 The page has expired due to inactivity. Please refresh and try again "The page has expired due to inactivity" - Laravel 5.5 How to increment a letter N times per iteration and store in an array? Can't install laravel installer via composer Only on Firefox "Loading failed for the <script> with source" Is there way to use two PHP versions in XAMPP? How to prevent page from reloading after form submit - JQuery laravel Eloquent ORM delete() method No Application Encryption Key Has Been Specified General error: 1364 Field 'user_id' doesn't have a default value How to logout and redirect to login page using Laravel 5.4? How to uninstall an older PHP version from centOS7 How to Install Font Awesome in Laravel Mix PDO::__construct(): Server sent charset (255) unknown to the client. Please, report to the developers Laravel - htmlspecialchars() expects parameter 1 to be string, object given How to downgrade php from 7.1.1 to 5.6 in xampp 7.1.1?

Questions with laravel tag:

Parameter binding on left joins with array in Laravel Query Builder Laravel 4 with Sentry 2 add user to a group on Registration Target class controller does not exist - Laravel 8 Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue? Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required How can I run specific migration in laravel Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory Artisan migrate could not find driver Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) laravel 5.5 The page has expired due to inactivity. Please refresh and try again "The page has expired due to inactivity" - Laravel 5.5 Can't install laravel installer via composer Laravel 5.4 Specific Table Migration laravel Eloquent ORM delete() method Including a css file in a blade template? laravel Unable to prepare route ... for serialization. Uses Closure Laravel 5.4 ‘cross-env’ Is Not Recognized as an Internal or External Command Vue js error: Component template should contain exactly one root element No Application Encryption Key Has Been Specified How to know Laravel version and where is it defined? General error: 1364 Field 'user_id' doesn't have a default value How to Install Font Awesome in Laravel Mix PHP7 : install ext-dom issue Laravel - htmlspecialchars() expects parameter 1 to be string, object given Laravel 5.4 create model, controller and migration in single artisan command Laravel Password & Password_Confirmation Validation Expected response code 250 but got code "535", with message "535-5.7.8 Username and Password not accepted Laravel: PDOException: could not find driver How to validate array in Laravel? Laravel Migration Error: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes Property [title] does not exist on this collection instance Composer: file_put_contents(./composer.json): failed to open stream: Permission denied Laravel Carbon subtract days from current date How to install all required PHP extensions for Laravel? if else condition in blade file (laravel 5.3) change the date format in laravel view page How to set the default value of an attribute on a Laravel model Extension gd is missing from your system - laravel composer Update laravel 5.3 new Auth::routes() The Response content must be a string or object implementing __toString(), "boolean" given after move to psql How to fix error Base table or view not found: 1146 Table laravel relationship table? "Please provide a valid cache path" error in laravel Setting selected option in laravel form Get only specific attributes with from Laravel Collection Get an image extension from an uploaded file in Laravel How to select specific columns in laravel eloquent