I am currently trying to figure out how I can implement a sorting feature for my mysql data being displayed in an html table. I already have the queries that I would need in order to achieve this, but I'm wondering how to now implement and switch between each of the queries when a user clicks on a particular column. I am using Laravel to build this project, so my data is being retrieved and compacted via a controller. Here is that controller and the queries I will need:
class StatController extends Controller
{
public function index()
{
//$stats = Stat::all();
$stats = Stat::orderBy('goals', 'DESC')->get();
//$stats = Stat::orderBy('goals', 'ASC')->get();
//$stats = Stat::orderBy('assists', 'ASC')->get();
//$stats = Stat::orderBy('assists', 'DESC')->get();
return view('stats.index', compact('stats'));
}
}
Here is the HTML table in my stats.index view:
<div class="all_tables stats_table table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Goals</th>
<th>Assists</th>
</tr>
</thead>
<tbody>
@foreach ($stats as $stat)
<?php
$player = App\Player::find($stat->player_id);
?>
<tr>
<td>{{ $player->number }}</td>
<td><a href="/players/{{ $player->id }}">{{ $player->fn }} {{ $player->ln }}</a></td>
<td>{{ $stat->goals }}</td>
<td>{{ $stat->assists }}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
How would I go about making the goals and the assists columns sortable on a user click?