Reputation: 25
I'm trying to make a sort for a project I'm doing, and I want to get the total of entries of my database and then make a select with the total of entries but ordered by 1 to 25 let's say..
My controller looks like this:
$users = User::orderBY('sort', 'DESC')->paginate(10);
return view('admin.user.index', compact('users'));
My view looks like this:
<select class="form-control" id="sort" name="sort">
@foreach($users as $user)
<option value="0">0</option>
@endforeach
</select>
Let's say I have 25 users. I want 25 options from 1 to 25 in the value, since I can't use the item id.. because they can be deleted.
Upvotes: 1
Views: 1770
Reputation: 4674
So you want to set the option's values from 1 to the total number of users? You can just simply update your foreach
block.
On your controller, fetch the user records:
$users = User::orderBy('sort', 'desc')->get();
return view('admin.user.index', compact('users'));
And update you view:
<select class="form-control" id="sort" name="sort">
@foreach($users as $index => $user)
<option value="{{ $index + 1 }}">{{ $index + 1 }}</option>
@endforeach
</select>
This way you can display an option with the value from 1 to the total number of users.
Note, if you don't really use any of user's properties on you view, you can just fetch the total number of users.
On your controller, fetch total number of users:
$totalUsers = App\Models\User::orderBy('id', 'desc')->count();
return view('test', compact('totalUsers'));
Then update your view like so:
<select class="form-control" id="sort" name="sort">
@for ($i = 1; $i <= $totalUsers; $i++)
<option value="{{ $i }}">{{ $i }}</option>
@endfor
</select>
Hope this answer you question.
Upvotes: 0
Reputation: 17668
You can try as:
<select class="form-control" id="sort" name="sort">
@foreach($users as $key => $user)
<option value="{{ $key + 1 }}">
{{ $key + 1 }}
</option>
@endforeach
</select>
Upvotes: 1