2 weeks ago

Laravel One to One - delete old record on creating new one

Posted 2 weeks ago by MidhunMonachan

I have an OTP model for User with One to One Relationship.

I generate the new OTP by

(new Otp())->setUser($user)->refreshOtp();

Following is the Otp model class

public $fillable = ['otp'];

     * Get the user from the OTP
    public function user(){
        return $this->belongsTo('App\Models\User');

    public function setUser(User $user) {
        return $this;

    public function refreshOtp() {
        $this->otp = substr(md5(microtime()), 0, 6);

But everytime I run (new Otp())->setUser($user)->refreshOtp(); it creates new record so a user end up having multiple otp records. I realize that I can query for the latest record, but I would like to know if there is a way to delete old records so I don't end up having a daaaaaaaaaatabase instead of a database

Please sign in or create an account to participate in this conversation.