Ad

How Can I Check If Laravel Count Result Is Null Or Not

- 1 answer

I have this code :

$status = htransaksi::find(auth()->user()->id)->where('Status','Open')->count();
if ($status != 0)
{
    $idhtrans = htransaksi::select('id')->where('User_ID', auth()->user()->id)->where('Status', 'Open')->first();
    $shopcart = DB::table('detiltransaksis')->join('Barangs', 'Barangs.id', '=', 'detiltransaksis.barang_Id')->where('htrans_Id', $idhtrans->id)->get();
    return view('home')->with('barang', $barang)->with('jenis', $jenis)->with('shopcount',$shopcart);
}
else
{
    return view('home')->with('barang', $barang)->with('jenis', $jenis);
}

This code checks, is there any item in your shopping cart? If there is an item then return that shopping cart and when there is no item it shows some error that say

Call to a member function where() on null

Anyone knows how to fix this? I'm new to Laravel and sorry if this is such a newbie question.

Edit : The error point to

 $status = htransaksi::find(auth()->user()->id)->where('Status', 'Open')->count();
Ad

Answer

As I see htransaksi::find(auth()->user()->id)->where('Status','Open')->count(); is incorrect. You cannot use where() function after find().

Let's try:

$status = htransaksi::where('User_ID',auth()->user()->id)->where('Status','Open')->count();
Ad
source: stackoverflow.com
Ad