D
D
dmytrotus2019-09-04 14:25:56
Laravel
dmytrotus, 2019-09-04 14:25:56

How to assign a number to a user by rating and display it in the blade?

Hi all.
There is a project on laravel
Here is the database migration

Schema::create('gamers', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('nick');
            $table->string('time');
            $table->timestamps();
        });

Here is the controller
public function index()
    {
    	return view('game')
    	->with('gamers', Gamer::all());
    }

Such a blade
<table class="table table-striped">
  <thead>
    <tr>
      <th scope="col">Позиция</th>
      <th scope="col">Nick</th>
      <th scope="col">Время</th>
      <th scope="col"></th>
    </tr>
  </thead>
  <tbody>
  @foreach ($gamers as $g)
    <tr>
      <th scope="row">1</th>
      <td>{{ $g->nick }}</td>
      <td>{{ $g->time }}</td>
      <td></td>
    </tr>
  @endforeach
  </tbody>
</table>

I need to display the position in the ranking and sort users in turn
, that is, whoever has less time is higher in the ranking and who has number 1,
and so on.
Tell me, how can this be done?
Something doesn't come to mind.
I remember that there is a sortBy () method and you can do this
@foreach ($gamers->sortBy('time') as $g)
    <tr>
      <th scope="row">1</th> //// но как менять тут 1,2,3,4 внутри foreach
      <td>{{ $g->nick }}</td>
      <td>{{ $g->time }}</td>
      <td></td>
    </tr>
  @endforeach

But how to change here 1,2,3,4 inside foreach

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Anton, 2019-09-04
@Fragster

First, in the controller, you can immediately get the sorted data:

public function index()
    {
    	return view('game')
    	->with('gamers', Gamer::orderBy('time', 'desc')->get()); // ну или создать дефолтный отсортированный скоуп, если это всегда требуется
    }

Secondly,
@foreach ($gamers as $index=>$g)
    <tr>
      <th scope="row">{{$index + 1}}</th>
      <td>{{ $g->nick }}</td>
      <td>{{ $g->time }}</td>
      <td></td>
    </tr>
  @endforeach

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question