#SQL reads `null` on required parameter value

12 messages · Page 1 of 1 (latest)

tired ingot
#

ItemsController:

public function save_item(Request $request, $id)
{
  $validator = Validator::make($request->all(), [
    'name' => ['required', 'string', 'max:255'],
    'description' => ['required', 'string']
  ]);

  if($validator->fails()) {
    return response([
      'success' => false,
      'message' => 'Database failed.'
    ], 403);
  }

  $data = [
    'item_id' => (int) $id, // sql reads this as null, it should be integer
    'name' => $request->input('name'),
    'description' => $request->input('description')
  ];

  $newItem = new Item($data);
  $result = $newItem->save();

  if(!$result) {
    return response([
      'success' => false,
      'message' => 'Database failed.'
    ], 403);
  }

  return response()->json([
    'success' => false,
    'data' => $result
  ]);
}

web.php:

Route::post('/items/{id}', [ItemsController::class, 'save_item'])->('item.save');

script.js

$('#new-item-form').on('submit', function(e) {
  e.preventDefault();

  var name = $('input[name=name]').val();
  var description= $('input[name=description]').val();

  $.ajax("{{ route('item.save', ['id' => $id]) }}", {
    method: "POST",
    data: {
      name,
      description
    },
  });
});

On the ItemsController, when I return a response immediately like:

return response()->json([
  'id' => (int) $id
]);

it has a value, but on:

  $data = [
    'item_id' => (int) $id, // sql reads this as null, it should be integer
    'name' => $request->input('name'),
    'description' => $request->input('description')
  ];

  $newItem = new Item($data);
  $result = $newItem->save();

SQL returns: Column 'item_id' cannot be null.

lunar geode
#

probably you haven't added the field to the property $fillable?

tired ingot
#

on App\Item model

lunar geode
#

would you mind to share the full error log? especially the query generated, did the column item_id showed in the query?

#

Example

tired ingot
#

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'item_id' cannot be null (SQL: insert into items (item_id, name, description, updated_at, created_at) values (1, test, test, 2023-08-21 05:21:47, 2023-08-21 05:21:47))

#

Here's the migration file:

public function up()
{
  Schema::create('items', function (Blueprint $table) {
    $table->id();
    $table->foreignId('item_id')->references('id')->on('item_details_test')->cascadeOnDelete();
    $table->string('name');
    $table->text('description');
    $table->timestamps();
  });
}
lunar geode
#

can you share the model?

lunar geode
tired ingot
#

i will try it on a new project and see if it has an error

lunar geode
#

and query generated look fine as well, it did pass the item_id