vesunar's avatar

Sort by default on name ASC using Kyslik\ColumnSortable\Sortable

Is there a quick way to sort by ASC?

View Table:

<!-- Table of contacts -->
    <div class="container">
        <div class="row" >
            <table class="table table-hover" id="contactsTable">
                <thead>
                    <tr>
                        <th>@sortablelink('name', 'Contact Name')</th>
                        <th>@sortablelink('number', 'Phone Number')</th>
                        <th>                            
                        </th>
                    </tr>
                </thead>

            <!--Loop through all the cutomers and output them on the table-->
            @foreach($contacts as $contact)
                <tbody>
                    <tr>
                        <td>{{ $contact->name }}</td>
                        <td>{{ $contact->number }}</td> 
                        <td>
                            <a href="{{ route('contacts.edit', $contact->id) }}" class="btn btn-primary btn-sm">View</a>    
                        </td>
                    </tr>
                </tbody>
            @endforeach
            </table>
            
            <!-- Pagination -->
            {!! $contacts->appends(\Request::except('page'))->render() !!}
        </div>  
    </div>

Controller:

public function index(Contacts $contacts)
    {  

        $filter = request('filter', NULL);
        $contacts = NULL;

        //If the search field is empty. Query the 'Contacts' table where 'owner_id' is the same as the authenticaded id then return all contacts under that 'owner_id'.
        if ($filter == NULL)
            $contacts = Contacts::query()->where('owner_id', auth()->id())->sortable()->paginate(15);
        //If the table is being searched. Query the 'Contacts' table where 'owner_id' is the same as the authenticaded id then return the filtered table (WHERE 'name/number' LIKE %example% ).
        else
        $contacts = Contacts::query()->where('owner_id', auth()->id())->where('name', 'like', '%'.$filter.'%')
                                     ->orWhere('number', 'like', '%'.$filter.'%')
                                     ->sortable()->paginate(15);

        //Return the index view with filtered/unfiltered contacts table.
        return view('contacts.index')->withContacts($contacts);          
    }
0 likes
2 replies
RoboRobok's avatar
Level 7

The documentation clearly says how to do it:

You can set default sorting parameters which will be applied when URL is empty.

$users = $user->sortable('name')->paginate(10);
// produces ->orderBy('users.name', 'asc')

$users = $user->sortable(['name'])->paginate(10); 
// produces ->orderBy('users.name', 'asc')

$users = $user->sortable(['name' => 'desc'])->paginate(10);
// produces ->orderBy('users.name', 'desc')
1 like

Please or to participate in this conversation.