PHP code example of akaunting / laravel-sortable

1. Go to this page and download the library: Download akaunting/laravel-sortable library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

akaunting / laravel-sortable example snippets


use Akaunting\Sortable\Traits\Sortable;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use Sortable;
    ...

    public $sortable = [
        'id',
        'title',
        'author',
        'created_at',
    ];
    ...
}

public function index()
{
    $posts = Post::query()->sortable()->paginate(10);

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

$posts = $post->sortable(['author'])->paginate(10); // $post->orderBy('posts.author', 'asc')

$posts = $post->sortable(['title'])->paginate(10); // $post->orderBy('posts.title', 'asc')

$posts = $post->sortable(['title' => 'desc'])->paginate(10); // $post->orderBy('posts.title', 'desc')

class Post extends Model
{
    use Sortable;
    ...

    protected $fillable = [
        'title',
        'author_id',
        'body',
    ];

    public $sortable = [
        'id',
        'title',
        'author',
        'created_at',
        'updated_at',
    ];

    /**
    * Get the author associated with the post.
    */
    public function author()
    {
        return $this->hasOne(\App\Models\Author::class);
    }
    ...
}

class User extends Model
{
    use Sortable;
    ...

    public $sortable = [
        'name',
        'address',
    ];

    public function addressSortable($query, $direction)
    {
        return $query->join('user_details', 'users.id', '=', 'user_details.user_id')
                    ->orderBy('address', $direction)
                    ->select('users.*');
    }
    ...

public $sortableAs = [
    'nick_name',
];

$users = $user->select(['name as nick_name'])->sortable(['nick_name'])->paginate(10);
bash
php artisan vendor:publish --tag=sortable