W Al123
W Al123

Reputation: 3

Laravel Inserting Data to Database

I am still new to Laravel, so I am trying to learn it from a certain website and try inserting data into database mysql by using form.

this is the view code

<!DOCTYPE html>
<html lang="en">
 <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
 </head>
 <body>
    <h1>Form Tambah Data</h1>
    <form action="/home/simpan" method="post">
       {{ csrf_field() }}
       Nama <input type="text" name="nama" required="required"><br/>
       Umur <input type="number" name="umur" required="required"><br/>
       Kota <input type="text" name="kota" required="required"><br/>
       <input type="submit" value="Simpan Data">
    </form>
 </body>
</html>

and then this is the web.php code

Route::get('/', function () {
  return view('welcome');
});

Route::get('/home', 'HomeController@index');

Route::get('/profil', function (){
   return view('profil');
});

Route::get('/home/tambah','HomeController@tambahData');

Route::post('/home/simpan','HomeController@simpan');

And this one is the controller codes

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class HomeController extends Controller
{
   //
   public function index(){
      //mengambil data dari tabel siswa
      $mahasiswa = DB::table('mahasiswa')->get();
      //mengirim data ke view mahasiswa
      return view('mahasiswa', ['mahasiswa' => $mahasiswa]);
   }

   public function tambahData(){
      return view('form_data');
   }

   public function simpan(Request $request){
       DB::table('mahasiswa')->insert([
          'nama' => $request->nama,
          'umur' => $request->umur,
          'kota' => $request->kota
       ]);
       return redirect('/home');
   }
}

The table in database has 4 columns, "id_mahasiswa, nama, umur, kota" and I try to only insert the data to 3 columns. But then, it always shows this error.

"Field 'id_mahasiswa' doesn't have a default value"

Can anyone tell me the solution for this?

Upvotes: 0

Views: 206

Answers (2)

codeHysteria127
codeHysteria127

Reputation: 97

I reviewed you code. In your phpmyadmin change the "id_mahasiswa" column default value to null for example :)

Upvotes: 0

D. Simmons
D. Simmons

Reputation: 245

It appears possibly that your database column "id_mahasiswa" within your "mahasiswa" table has a NOT NULL constraint and no default value so when you are trying to insert your record without a value for "id_mahasiswa" your query fails.

If the above is true you need to either provide a value for the field or change the design of the table you are working with.

Upvotes: 1

Related Questions