Home > database >  Illuminate\Database\QueryException SQLSTATE[42S22]: Column not found: 1054 Unknown column
Illuminate\Database\QueryException SQLSTATE[42S22]: Column not found: 1054 Unknown column

Time:09-29

I was try about CRUD with Eloquent but there is an error when I run my program

Illuminate\Database\QueryException SQLSTATE[42S22]: Column not found: 1054 Unknown column 'pegawai.id' in 'where clause' (SQL: select * from pegawai where pegawai.id = 1 limit 1)

I just see my database is no problem but this happen when I want to run my program. And I attach my controller

    public function pegawai_edit($id)
        {
            $pegawai = Pegawai::find($id);
            return view('pegawai_edit', ['pegawai' => $pegawai]);
        }

and this is my web.php

Route::get('/pegawai/pegawai_edit/{id}', 'PegawaiController@pegawai_edit');

This is my pegawai table :

 ------------ -------------- ----------------- -------------- ---------------- --------------------- --------------------- 
| pegawai_id | pegawai_nama | pegawai_jabatan | pegawai_umur | pegawai_alamat | created_at          | updated_at          |
 ------------ -------------- ----------------- -------------- ---------------- --------------------- --------------------- 
|          1 | Lucas        | NULL            |            1 | Jakarta        | 2021-09-29 09:07:09 | 2021-09-29 09:07:09 |
|          2 | Test         | NULL            |            2 | TEST           | 2021-09-29 09:07:26 | 2021-09-29 09:07:26 |
 ------------ -------------- ----------------- -------------- ---------------- --------------------- --------------------- 

I'm using laravel 8.6 and mysql is my database

CodePudding user response:

By default, eloquent model use the field id as the primary key. Since you use pegawai_id instead, you need to set it in your model

class Pegawai extends Model
{
    /**
     * The primary key associated with the table.
     *
     * @var string
     */
    protected $primaryKey = 'pegawai_id';
}

once set, you can use all the methods eloquent provide without specificly telling it to use pegawai_id each time

public function pegawai_edit($id)
{
    $pegawai = Pegawai::find($id);
    return view('pegawai_edit', ['pegawai' => $pegawai]);
}

CodePudding user response:

As you don't respect the Laravel standard, i.e. use id as the name for your id column, try like this :

public function pegawai_edit($id)
        {
            $pegawai = Pegawai::where('pegawai_id', $id)->first();
            return view('pegawai_edit', ['pegawai' => $pegawai]);
        }

Or modify just your Pegawai model, adding :

protected $primaryKey = 'pegawai_id';
  • Related