First Laravel project. I have a controllerfunction what checks if there any record with that barcode. If no insert a record. If yes add one for the count.
public function sellmode(Request $request){
    $barcode=$request->barcode;
    $test = DB::select('select count from sellmode where barcode = ?', [$barcode]);
    $row_cnt = mysqli_num_rows($test);
    if ($row_cnt == 0) {
        Debugbar::info('Új sor');
        DB::insert('insert into sellmode (barcode, count) VALUES (?, ?)', [$barcode, '1']); 
    } else {
        Debugbar::info('Meglévő frissítése');
        DB::update('update sellmode set count = count + 1 WHERE barcode = ?' [$barcode]);
    }
    return view(sell);
}
When I tried it, it had the following error:
ErrorException in SellController.php line 17: mysqli_num_rows() expects parameter 1 to be mysqli_result, array given
What did I wrong?
You can't just just mysql_num_rows on a Laravel query builder. Laravel query builder will return a collection, so you can just use the isEmpty function to find out if it has any results.
if ($test->isEmpty()) {
    Debugbar::info('Új sor');
    DB::insert('insert into sellmode (barcode, count) VALUES (?, ?)', [$barcode, '1']); 
} else {
    Debugbar::info('Meglévő frissítése');
    DB::update('update sellmode set count = count + 1 WHERE barcode = ?' [$barcode]);
}
If you are using a Laravel version pre-5.3, the query builder will return an array. In this case, you can use the php count function on this array to know how many rows are returned
if (count($test) === 0) {
    Debugbar::info('Új sor');
    DB::insert('insert into sellmode (barcode, count) VALUES (?, ?)', [$barcode, '1']); 
} else {
    Debugbar::info('Meglévő frissítése');
    DB::update('update sellmode set count = count + 1 WHERE barcode = ?' [$barcode]);
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With