Laravel 6 - Unique custom id doesn't increment after table get empty

Viewed 279

Current Situation

I have custom unique increment makes the code looks like this

enter image description here

but when i make that table empty and add new value it looks like this

enter image description here

Expected Situation

after I made the table empty and make new input the custom_id should follow the id

enter image description here

The Model

    class Transaction_in extends Model
    {
        protected $table = 'transaction_ins';
        protected $primaryKey = 'idTransactionsIN';
        public $timestamps = true;
        public $incrementing = false;
        protected $guarded = [];

    public static function getidTransactionsIN(){
        DB::table('transaction_ins')->orderBy('id','desc')->take(1)->get();
    }
}

The Controller

public function store(Request $request)
{
    $request->validate([
        'transaction_in_date' => 'required',
    ]);

    Transaction_in::getidTransactionsIN();

    $newtransaction_inId = Transaction_in::max('id') + 1;
    $Getnewtransaction_inId = sprintf('TIN%04d', $newtransaction_inId);

    $transaction_in = new Transaction_in();
    $transaction_in->idTransactionIN = $Getnewtransaction_inId;
    $transaction_in->date = $request->input('transaction_in_date');
    $transaction_in->save();
}
1 Answers

You can set custom_id after creating model and it's a bit safer in case of many operations:

public function store(Request $request)
{
    $request->validate([
        'transaction_in_date' => 'required',
    ]);


    $transaction_in = Transaction_in::create(['date' => $request->input('transaction_in_date')]);

    $transaction_in->update(['custom_id' => sprintf('TIN%04d', $transaction_in->id)]);
}

you should also just in case wrap it in database transaction.

Related