简体   繁体   中英

How to insert data to database with Laravel

I'm trying to insert my data to database from form.

My URL to create the data is web.com/siswa/create

But when I click submit system show error MethodNotAllowedHttpException .

How I can fix it? Is there anything wrong with my code?

Here is my form:

<form action="{{ url('siswa') }}" method="POST">
      <div class="form-group">
         <label for="exampleInputEmail1">NISN</label>
          <input type="text" class="form-control" name="nisn" id="nisn" placeholder="NISN"></div>
         <div class="form-group">
         <label for="exampleInputEmail1">Nama Siswa</label>
         <input type="text" class="form-control" name="nama_siswa" id="nama_siswa" placeholder="Nama Siswa"> </div>
         <button type="submit" class="btn btn-success btn-sm font-weight-bold">Submit</button></form>

Controller:

public function tambah()
    {
      return view('siswa.create');
    }

    public function store(Request $request)
      {

        $siswa = new \App\Siswa;
        $siswa->nisn = $request->nisn;
        $siswa->nama_siswa = $request->nama_siswa;
        $siswa->tanggal_lahir = $request->tanggal_lahir;
        $siswa->jenis_kelamin = $request->jenis_kelamin;
        $siswa->save();
        return redirect('siswa');
      }

Route:

Route::get('/siswa/create', [
    'uses' => 'SiswaController@tambah',
    'as' => 'tambah_siswa'
]);

Route::get('/siswa', [
    'uses' => 'SiswaController@store',
    'as' => 'simpan_siswa'
]);

change your store function route from get to post

Route::post('/siswa', [
'uses' => 'SiswaController@store',
'as' => 'simpan_siswa'
]);

Use Csrf protection field in your form for the session timeout error

{{ csrf_field() }}

OR

<input type="hidden" name="_token" id="csrf-token" value="{{ Session::token() }}" />

OR if you are using Form builder

{!! Form::token() !!}

In Route please use post instead of get

Route::post('/siswa','SiswaController@store');

and also include {{ csrf_field() }} in form

you are using method="POST" on your form but in on your route you are using Route::get

Use Route::post for your route

In your form you've given POST method, but your router doesn't have any POST handler. So all you have to do is , when you are trying to store data from form to DB you have to post the data, and the router should handle it.

Try this

Route::post('/siswa', [
'uses' => 'SiswaController@store',
'as' => 'simpan_siswa'
]);

You are using POST method in your form and using GET in route.

try this

Route::post( '/siswa', [
    'uses' => 'SiswaController@store',
    'as'   => 'simpan_siswa'
] );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM