Laravel:嵌套两个foreach语句,选择带有Optgroups的字段

I want to create a select field with optgroups

$spec = DB::table('agentspec')->orderBy('category', 'desc')->get();

The table has three columns

category, spec, agentdesc

The optgroup label is "category" with "spec" as the select value

This is what I've tried getting error Trying to get property of non-object

@foreach($spec as $spec)
    @if ($spec->category == 'Agent')
<optgroup label="Agent">
 @foreach($spec as $spec)
<option value="{{ $spec->spec}}">{{ $spec->spec }}{{ $spec->agentdesc }}</option>
@endforeach
    </optgroup>
 @endif
       @endforeach

You need to rename your iterator variable here, it can't be in par with the collection:

@foreach($spec as $spec)