1

In the official documentation I can see a method destroy where you can put a list of Primary Keys and it deletes all the data in the list.

ModelName::destroy([1,2,3]);

But what if we have a custom PK? I've tried to do it with a field called code which is a string but it says:

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

Is there a way to tell Laravel that the primary key is not called id?

Something like

ModelName::destroy(['AL', 'ES', 'FR'], 'code');
3
  • So code is the actual primary key for the table, or are you just wanting to delete multiple records where code is AL, ES or FR`? Commented Jun 25, 2018 at 12:07
  • In my models I have $table->string('code', 4)->primary(); so It is the actual primary key Commented Jun 25, 2018 at 12:13
  • 1
    In that case @yivi's answer should work for you. Commented Jun 25, 2018 at 12:14

1 Answer 1

2

From the documentation:

Eloquent will also assume that each table has a primary key column named id. You may define a protected $primaryKey property to override this convention.

So, in your model:

class User extends Model
{

    protected $primaryKey = 'yourPrimaryKey';
}

Since it appears you are using a string-based PK, the following paragraph in the docs is also relevant.

In addition, Eloquent assumes that the primary key is an incrementing integer value, which means that by default the primary key will be cast to an int automatically. If you wish to use a non-incrementing or a non-numeric primary key you must set the public $incrementing property on your model to false. If your primary key is not an integer, you should set the protected $keyType property on your model to string.

So your model should also include:

protected $incrementing = false;
protected $keyType      = 'string';
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.