[Solved] Using insert with condition on laravel [closed]


Well the reason it inserts twice is you make an DB::insert() and also create a new book using $book->save()

This should work better:

$book = new Book;
$ta = DB::table('book')->selectRaw('MAX(ta) AS ta')->first()->ta;
if($ta == 0){
    $book->ta = 1;
    $book->tb = 1;
}
else {
    $tb = DB::table('book')->selectRaw('MAX(tb) AS tb')
            ->where('ta', $ta)->first()->tb;
    if($tb <= 20){
        $book->ta = $ta;
        $book->tb = $tb + 1;
    }
    else {
        $book->ta = $ta + 1;
        $book->tb = 1;
    }
}
$book->save();

solved Using insert with condition on laravel [closed]