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");
}
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');
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With