Home > Net >  Laravel Custom Primary Key not working on Data Update
Laravel Custom Primary Key not working on Data Update

Time:10-25

I am trying to make a crud function in laravel with custom primary ID. The Create, Read, and Delete are all working but whenever I tried Update I get an error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select count(*) as aggregate from pages where slug = about and id <> 3)

Model pages.php

class Page extends Model{
use HasFactory;

protected $primaryKey = 'pages_id';

protected $fillable = [
    'is_default_home',
    'is_default_not_found',
    'title',
    'slug',
    'content',
];}

Controller pages.php

public function update()
{
    $this->validate(); 
    $this->unassignedDefaultHomePage(); 
    $this->unassignedDefaultNotFoundPage(); 
    Page::find($this->modelId)->update($this->modelData());
    $this->modalFormVisible = false;
    $this->reset();
}

Model Data

public function modelData()
{
    return [
        'title' => $this->title,
        'slug' => $this->slug,
        'content' => $this->content,
        'is_default_home' => $this->isSetToDefaultHomePage,
        'is_default_not_found' => $this->isSetToDefaultNotFoundPage,
    ];
}

I'm not sure why it finds the column 'id' because I set the $primaryKey in my model as 'pages_id'. I am using phpMyAdmin (xampp).Thank you for your help!

CodePudding user response:

Check your database table columun id doesn't exists. Create acolumn in database.

class Page extends Model{
use HasFactory;

protected $primaryKey = 'pages_id';

protected $fillable = [
    'is_default_home',
    'is_default_not_found',
    'title',
    'slug',
    'content',
];}

In Above code pages_id prefer to table named pages column named id. Check these

CodePudding user response:

This is a error from count query, not from update query. I think you need check other function. Update function is no problem.

  • Related