Skip to content
Advertisement

insert to database (mysql) don’t work in Laravel

Inserting data into database in laravel don’t work. PHP Controller code:

public static function publish (Request $request) {
    $autor = session("name")." ".session("surname");
    $title = $request->title;
    $title2 = $request->title2;
    $titlePhoto = $request->titlePhoto;
    $text = $request->text;
    $category = $request->category;
    $tag = $request->tag;
    $source = $request->source;
    DB::table("articles")->insertGetId(
        ["title" => $title, "autor" => $autor, "text" => $text, "title2" => $title2, "category" => $category, "titlephoto" => $titlePhoto, "tag" => $tag, "source" => $source]
    );
}

The request data are received by the controller.

I have in table another column: date but i want to keep them empty. Laravel won’t let me leave them empty. Display error: Field ‘date’ doesn’t have a default value

if I change “DB::table(“articles”)->insertGetId…” to “DB::insert(“INSERT INTO articles (title, autor, title2, category, titlephoto, tag, source) VALUES (‘$title’, ‘$autor’, ‘$title2’, ‘$category’, ‘$titlePhoto’, ‘$tag’, ‘$source’)”);” it doesn’t work either, but it doesn’t return the error.

Why doesn’t it work?

Advertisement

Answer

If you want to empty date field you have 2 option:

1.add this key to insert array as blank "date" => ""

OR

2.modify date column as nullable

ALTER TABLE your_table MODIFY date DATETIME
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement