I am experiencing some weird issue with updating records in Laravel. I use this code to update a record:
$student = new Student();
$student->exists = true;
$student->reg_number = $request->post('reg_number');
$student->name = $request->post('name');
$student->level_id = $request->post('level_id');
$student->status = $request->post('status');
$student->save();
The code executes fine for the first time. However, when I try to update the same record again, I get the error
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'F17/2019/2019' for key 'PRIMARY' (SQL: insert into
students(reg_number,name,level_id,updated_at,created_at) values (F17/2019/2019, John Does, 5, 2019-08-08 10:31:52, 2019-08-08 10:31:52)).
However, after sometime, say half an hour or so, I can update the record again without the error, but only once. A second try brings back the error.
I have tried various other techniques discussed in this question, but the results are identical. The error suggests that Laravel is opting to use INSERT instead of UPDATE SQL statement, whereas the record exists and I have explicitly specified that it should update an existing record.
Does anyone know what's going on here?
I am usng MySQL, my students table PRIMARY KEY is reg_number of type VARCHAR. The student controller looks like so:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
protected $fillable = [
'reg_number',
'name',
'level_id',
'status'
];
protected $primaryKey = 'reg_number';
public $incrementing = false;
}
exists, the code updates an existing record. Please follow the link in my question. Also, the fact that the record updates for the first time should hint you that the error isn't arising from usingnew Student().$wasRecentlyCreatedif you dig the source. The recommended way to get existing models is to hydrate them from the DB.existsproperty actually works in Laravel 5.8. Try it out.