Reputation: 149
i have postqs and users table. user_id is foreign key in postqs table . i have a form and after i submit the form all the data saving in database correctly. but it is not directing to index page its showing this ERROR:
SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into
Postqs
(question
,description
,solution
,image
,tags
,updated_at
,created_at
) values (hh, bb, bb, images .bmp.jpg, bb, 2017-09-20 08:14:32, 2017-09-20 08:14:32))
How i can solve it?
store controller function :
public function store(Request $request)
{
$this->validate($request, [
'question' => 'required',
'description' => 'required',
'tags' => 'required',
]);
$user = auth()->user();
$user->postqs()->create($request->all() );
$input = $request->all();
$tags = explode(",", $request->tags);
$postqs = Postqs::create($input);
$postqs->tag($tags);
return redirect()->route('postqs.index')
->with('success','Your question created successfully');
index controller function:
$postqs=Postqs::whereHas('user')->get();
return view('postqs.index',compact('postqs','users'));
postqs model:
protected $fillable =
['question','description','solution','image','tags','user_id'];
public function user(){
return $this->belongsTo("App\User"); }
User model:
public function postqs(){
return $this->hasMany("App\Postqs");
}
Upvotes: 4
Views: 13906
Reputation: 53
When i had this error, this was my solution from @Matius's answer
$user = auth()->user();
$data = $request->all();
$data['user_id']=$user->id;
Upvotes: 1
Reputation: 1
In my case, after a Mysql update, the indexes of the database were gone. I was getting the same error messages that we are talking about.
I had to recreate the indexes and make the id column on each table the primary key, and auto-increment.
After that... Everything, works.
Upvotes: 0
Reputation: 901
the field user_id in your table is not nullable, and you tried to save post without user_id, or may be user_id is not passed by request. Try this:
$this->validate($request, [
'question' => 'required',
'description' => 'required',
'tags' => 'required',
]);
$user = auth()->user();
$data = $request->all();
$data['user_id']=$user->id;
$user->postqs()->create($data);
$tags = explode(",", $request->tags);
$postqs = Postqs::create($data);
//$postqs->tag($tags);
$postqs->tag()->save($tags);
return redirect()->route('postqs.index')
->with('success','Your question created successfully');
Upvotes: 5
Reputation: 493
Did you add a user to your database? Please add a user and then you must add user_id
to $fillable
.
Upvotes: 0
Reputation: 12953
you did not post your table's schema, but from the error it seems that you have a field user_id
which is set as non-null and does not have a default value- which means every insert query must provide its value.
The solution - either give the column a default value, or pass it in your query
Upvotes: 1