custom primary key in Laravel not working

I've set a custom primary key in my Task.php model.

class Task extends Model
{
    //

    protected $primaryKey = 'taskn';
    public $incrementing = false;

}

I've also set taskn as my primary key in the migration:

$table->string('taskn');

$table->primary('taskn');

But I still get the error

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from `Task` where `id` = 1 limit 1)

For some reason Laravel still tries to query id.

I am trying to retrieve the data with the following call:

$tasks = DB::table('tasks')->find($taskn);

What is wrong here?

1 answer

  • answered 2018-04-14 14:30 ceejayoz

    I'm doing $tasks = DB::table('tasks')->find($taskn);

    Here's your problem.

    DB:: calls don't use Eloquent - you're completely bypassing it. If you do Task::find($taskn) it'll work, but DB:: calls have no idea about your $primaryKey settings.