Mahmoud Niypoo
Mahmoud Niypoo

Reputation: 1720

set id value in AUTO_INCREMENT field with laravel

I have tried to set value id of new row in laravel 5 , by Point::create($value) and new Point($value) the $value contains a id value and this id doesn't exist in mysql db. and every time I try the new row has got a auto id not that in $value

Upvotes: 5

Views: 11846

Answers (3)

Mykola Vasilaki
Mykola Vasilaki

Reputation: 435

If you don't want to make id fillable, than you can use next instead of Point::create($value):

$point = Point::make($value);
$point->id = $value['id'];
$point->save();

Also you can Point::unguard() to temporarily disregard the fillable status of fields and make id temporary fillable.

Upvotes: 1

Sohel0415
Sohel0415

Reputation: 9863

Add id in your fillable array in Point model class.

protected $fillable = [
    'id'
];

Upvotes: 8

Alexey Mezenin
Alexey Mezenin

Reputation: 163978

You need to set a custom primary key with:

protected $primaryKey = 'custom_key';

If you don't have PK, do this:

protected $primaryKey = null;
public $incrementing = false;

Also, remove it from fillable() array. In this case, id will be ignored.

From the docs:

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.

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.

Upvotes: 1

Related Questions