i want to make code with 4 digit auto increment integer and current date format MMMyy that has to use carbon. Example: Oct22-0001, Set22-0002, Dec22-0003.
table producs
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('nama_barang');
$table->string('kode', 10);
$table->double('harga');
$table->integer('jumlah');
$table->timestamps();
});
}
ProductController
public function store(Request $request)
{
$storeData = $request->all();
$validate = Validator::make($storeData, [
'nama_barang' => 'required|max:60|unique:products',
'harga' => 'required|numeric',
'jumlah' => 'required|numeric'
]);
$lastValue = Product::orderBy('kode', 'desc')->first();
$storeData = new Product();
$date = Carbon::now();
$storeData->kode = $date . '-' . str_pad($lastValue->kode, 4, '0', STR_PAD_LEFT) + 1;
if($validate->fails())
return response(['message' => $validate->errors()], 400);
$product = Product::create($storeData);
return response([
'message' => 'Add product Success',
'data' => $product
], 200);
}
i got error
"message": "Illuminate\Database\Eloquent\Builder::create(): Argument #1 ($attributes) must be of type array, App\Models\Product given, called in C:\Users\nana\test\vendor\laravel\framework\src\Illuminate\Support\Traits\ForwardsCalls.php on line 23",
Product. if you already have an instance ofProduct, you might want to call->save()on the instance instead. see docs.$lastValuerisks having race condition. you should use transaction to ensure no duplicates. though, if you set thatkodecolumn as unique you can handle the exception thrown should thekodealready used.