Home > database >  How to improve the loop
How to improve the loop

Time:10-19

What should I add to the code so that it checks the values ​​in the array one by one

<table style="width:100%">
<tr>
    <th>Price</th>
    <th></th>
</tr>
@foreach ($items as $item)
    <tr>
        <th>{{ $item->stock }}</th>
        <th>{{ $result }}</th>
    </tr>
@endforeach
    public function index(items $items)
{
    $items = DB::table('items')->get();

    $item = DB::table('items','stock')->pluck('stock');

    if ($item ->count() > 1){
        $resoult = 'true';
    }else{
        $resoult = 'false';
    }
    dd($item);

    return view('items.items', [
        'items' => $items,
        'resoult' => $resoult
    ]);
}

enter image description here

enter image description here

CodePudding user response:

I’m not entirely sure what you are after but if you just want to loop over the $items array just write the following code

foreach ($items as $item) {
    dd($item)
}

Inside the {} brackets you can check each value one by one by using the $item variable.

CodePudding user response:

public function index(items $items)
{
    $items = DB::table('items')->where(['stock', '>', 0])->get();

    // ->where(['stock', '>', 0]) this will filter items which have stock 
    // greater then 0, so you will not need to filter them with PHP
    
    // ->get() will return "collection"
    // ->first() will return first row from database that matches query

    return view('items.items', [
        'items' => $items
    ]);
}

You can reduce number of lines of code like this:

public function index(items $items)
{
    return view('items.items', [
        'items' => DB::table('items')->where(['stock', '>', 0])->get()
    ]);
}
  • Related