edit this page Ordering

Ordering can be setup by using the $orderable variable in your repository. The $orderable variable contains the names of the table columns that are used for ordering.

Also see Global Scopes under Scope for more Ordering magic.

<?php

namespace App\Repositories;

use Torann\LaravelRepository\Repository;

class UsersRepository extends Repository
{
    /**
     * Specify Model class name
     */
    protected string $model = \App\User::class;

    /**
     * Orderable columns.
     */
    protected array $orderable = [
        'name',
        'confirmed',
        'user_role_id',
        'created_at',
    ];
}

How this works in our controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Repositories\UserRepository;

class UsersController extends Controller
{
    protected UserRepository $repository;

    public function __construct(UserRepository $repository)
    {
        $this->repository = $repository;
    }

    /**
     * Display a listing of the resource.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Contracts\View\View
     */
    public function index(Request $request)
    {
        $users = $this->repository
            ->orderBy($request->get('sort'), $request->get('dir'))
            ->paginate();

        return view('users.index')->with([
            'users' => $users,
        ]);
    }
}

Masking Table Columns

To hide the true name of the table column, we simply create a key/value pair. Where the key is the name of the parameter the user sees and the value is the name of the table column.

<?php

namespace App\Repositories;

use Torann\LaravelRepository\Repository;

class UsersRepository extends Repository
{
    /**
     * Specify Model class name
     */
    protected string $model = \App\User::class;

    /**
     * Orderable columns.
     */
    protected array $orderable = [
        'name',
        'confirmed',
        'role' => 'user_role_id',
        'created_at',
    ];
}

Another benefit of doing this is that it allow us to sort by joined tables as well. Just simply prefix the column name with the table name.