Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this ERROR: General error: 1364 Field 'user_id' doesn't have a default value

Tags:

php

mysql

laravel

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");
    }
like image 996
kavi Avatar asked Mar 09 '23 00:03

kavi


2 Answers

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');
like image 99
Matius Nugroho Aryanto Avatar answered Apr 27 '23 11:04

Matius Nugroho Aryanto


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

like image 21
Nir Levy Avatar answered Apr 27 '23 11:04

Nir Levy