Ad

Blade Template And Radio Buttons - Select First In Foreach Loop

- 1 answer

I have the following Blade template entry, which creates (as part of a table row) a column of radio buttons.

I want to have only the first radio genereated selected, and I want to do this via the PHP, no js post page load.

How do I check if this is the "first" entry in my collection and thus place the string checked as an attribute in the HTML? My latest code permutation is below, but it does not work.

@foreach ($organisationsOwned as $organisationOwned)
    <tr class="organisations-table">
        <td><input type="radio" name="organisations" id="{!! $organisationOwned->id !!}" @if ($organisationsOwned{0}) {!! "checked" !!} @endif></td>
        <td>{!! $organisationOwned->org_title !!}</td>
        <td>{!! $organisationOwned->plan_title !!}</td>
        <td style="text-align: center;">{!! currency_format($organisationOwned->gst_amount) !!}</td>
        <td style="text-align: right;">{!! $organisationOwned->subscription_ends_at !!}</td>
    </tr>
@endforeach

More precisely, here's the line for the input:

<input type="radio" name="organisations" id="{!! $organisationOwned->id !!}" @if ($organisationsOwned{0}) {!! "checked" !!} @endif>

I have tried variations such as:

{{ head($organisationsOwned) ? checked : '' }}>

and

{{ $organisationsOwned{0} ? checked : '' }}>

and even this suggestion shown as a working model of my question:

@if ($organisationOwned == reset($organisationsOwned)) checked @endif

Thanks and happy new year!

Ad

Answer

If you did not specify keys for the elements of $organisationsOwned you can use the element's index to determine if it's the first one:

@foreach($organisationsOwned as $index => $organisationOwned)
  ...
  <td><input type="radio" name="organisations" id="{!! $organisationOwned->id !!}" @if (!$index) {!! "checked" !!} @endif></td>
  ...
@endforeach
Ad
source: stackoverflow.com
Ad