0

In my resource controller, in the store method, I do this:

public function store(Request $request)
    {
      $post = $request->all();
      $post['user_id'] = Auth::user()->id;

      Post::create($post);

        return redirect()->route('index');
    }

Why am I getting the error: General error: 1364 Field 'user_id' doesn't have a default value?

3
  • try put static ` $post['user_id'] = 4;` and check Commented Jan 20, 2021 at 7:08
  • is your user actually logged in? return Auth::user()->id and see whats inside Commented Jan 20, 2021 at 7:18
  • Yes, he is logged in. The problem was that I hadn't added the user_id to the protected $fillable. Commented Jan 20, 2021 at 7:20

2 Answers 2

1

you should add 'user_id' to the $fillable attribute in your Post model to support mass assignment

class Postextends Model

{
protected $fillable=['user_id']; // not only user_id but also all the fill able columns
} 
Sign up to request clarification or add additional context in comments.

1 Comment

Really! Thank you! For some reason I thought that we need to add to $fillable only those fields that we get from input.
0

you shuold use user_id in fillable like this,

class Postextends Model
{
    protected $fillable=['user_id'];
} 

And also you can set $guarded property as,

class Postextends Model
{
    protected $guarded=[];
}

Then you not need to set propertise filable.

Note: While $fillable serves as a “white list” of attributes that should be mass assignable, you may also choose to use $guarded. The $guarded property should contain an array of attributes that you do not want to be mass assignable. All other attributes not in the array will be mass assignable. So, $guarded functions like a “black list”. Of course, you should use either $fillable or $guarded — not both.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.