0

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?

1
  • 1
    I may suggest you to use DataTables if you want something simple. Commented Jul 2, 2017 at 2:48

1 Answer 1

2

Use DataTable plugin in JQuery, You just need to use datatable js file from here

your table should be something like this:

<table id="myTable">
    <thead>
        <tr>
              <th></th>
              ...
              ...
              <th></th>
        </tr>
   </thead>

   <tbody>
        <tr>
             <td></td>
             ...
             ...
            <td></td>
       </tr>
  </tbody>

After adding js file, you have to add this script.

$(document).ready(function(){
   $('#myTable').DataTable();
});
Sign up to request clarification or add additional context in comments.

4 Comments

Awesome! Thank you!!
Congrats, Glad it helped you
Bad for dealing with a lot of data/records
@Ratto Ajax is best option for datatable ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.