Ad

I Can't Submit Data Into Database In Laravel

- 1 answer

I am new to Larave and using Laravel Framework 6.17.1. I am getting this error when submitting data to the database using the form. Bellow is the error I am getting.

Illuminate\Database\QueryException SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into posts (title, updated_at, created_at) values (Header, 2020-03-27 07:55:06, 2020-03-27 07:55:06))

PostContolller.php

 public function create()
{
    //
    return view('posts.create');
}

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    //
    //return $request->all();
    Post::create($request->all());
}

Table

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->integer('user_id')->unsigned();
        $table->string('title');
        $table->text('content');
        $table->timestamps();
    });
}

Route

Route::resource('/posts', 'PostController');

Ad

Answer

The reason you are getting that error it's because the user_id column is not nullable. To solve the issues ensure the following:

1) In Post Model add the following fillable:

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

3) In your PostController.php, you must have the following constructor. To ensure the only user who is authenticated can create a post.

 public function __construct()
{
    $this->middleware('auth');
}

2) I am assuming that the user submitting the form is an authenticated user in your application. Hence, in the blade where you have your form add the following line of code:

<input type="hidden" name="user_id" value="{{ Auth::user()->id }}">

In the above piece of code, we are passing a hidden filled which contains your user_id value which gets from Laravel Auth facade.

Now when you dd($request->all()); you should be able to see user_id in your array.

NB: When using mass assignment you need to add protected fillable on your model and ensure the name you use in input filled to match the exact name in your model. Learn more about Laravel mass assignment

Ad
source: stackoverflow.com
Ad