Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/fusic/laravel-sortable


https://github.com/fusic/laravel-sortable

Last synced: 2 months ago
JSON representation

Awesome Lists containing this project

README

        

# Laravel-Sortable
Easily generate a link to switch the sort state for `` and so on.

## Install
Add this repository to `composer.json` then `$ composer install`.
```
"repositories": [
{
"type": "vcs",
"url": "git@github.com:fusic/laravel-sortable.git"
}
]
```

Register the Service Provider to `config/app.php`.
```
'providers' => [
...
/*
* Package Service Providers...
*/
Sortable\Providers\SortableServiceProvider::class,
...
]
```

## Usage
### Create Sortable class
Execute artisan `make:sortable` command.

```
$ php artisan make:sortable EmployeeSortable
```

### Settings
Write sort keys in the created `Sortable` class.

```
params = [ // write here!
'employee_number',
'name' => 'Employees.fullname', // URL parameter => column name
'birthday' => function ($builder, $query, $sortKey, $sortDirection) {
// write custom 'order by' condition
return $builder->orderBy('foo', 'desc');
},
];
}
}
```

### Insert a Sortable object to the query

```
$employees = Employees::query()
->where('foo', 'baz')
/** what you want... **/
->sort(new EmployeeSortable())
/** ... **/
;
```

This will add the sort condition to the query. `Sortable` can be used in both Eloquent and Query Builder.

### Use @sort directive in the blade
#### Generate a simple link
```
@sort(['title' => 'Name', 'key' => 'name', 'url' => '#'])
```

This `@sort` directive will generate a link to switch the sort state like this:

```
Name
```

The state switches in the order of ascending, descending, and unsorting, the generated links follow the order.

Usage example:

```



@sort(['title' => 'Number', 'key' => 'employee_number', 'url' => '#'])
@sort(['title' => 'Name', 'key' => 'name', 'url' => '#'])
@sort(['title' => 'Birthday', 'key' => 'birthday', 'url' => '#'])



@foreach($employees as $employee)

{{ $employee->employee_number }}
{{ $employee->fullname }}
{{ $employee->birthday->format('Y/m/d') }}

@endforeach

```

#### Generate a link with custom DOM template
Passing the DOM templates corresponding to each sort state to `@sort` directive, `Sortable` will generate links according to it.

```
@sort([
'key' => 'name',
'default' => 'Name',
'asc' => 'Name↑',
'desc' => 'Name↓',
])
```

This will generate a custom link:

```
Name↑
```