Skip to content

Instantly share code, notes, and snippets.

@uno-de-piera
Last active Jun 4, 2019
Embed
What would you like to do?
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
protected $guarded = ['id'];
public function role () {
return $this->belongsTo(Role::class);
}
public function scopeFiltered ($query, $paginated = true) {
$search = request('search');
$sortBy = request('sortBy');
$order = request('descending') == 'true' ? 'desc' : 'asc';
$role = request('role');
$active = request('active');
$query->select(
'id', 'role_id', 'username', 'firstname', 'lastname', 'email', 'phone_number', 'active'
)
->with(
[
'role' => function ($query) {
$query->select('id', 'name');
}
]
);
if ($role != 'null') {
$query->whereHas('role', function ($query) use ($role) {
$query->where('name', $role);
});
}
if ($active != 'null') {
switch ($active) {
case 'Desactivado': {
$query->where('active', 0);
break;
}
case 'Activado': {
$query->where('active', 1);
break;
}
}
}
if ($search) {
$query->where('username', 'LIKE', "%$search%")->orWhere('firstname', 'LIKE', "%$search%")->orWhere('lastname', 'LIKE', "%$search%")->orWhere('email', 'LIKE', "%$search%");
}
switch ($sortBy) {
case 'username':
case 'firstname':
case 'lastname':
case 'email': {
$query->orderBy($sortBy, $order);
}
}
return $query;
}
}
<?php
namespace App\Http\Controllers;
use App\Role;
use App\User;
class UserController extends Controller
{
public function filters () {
$statuses = [
0 => 'Desactivado',
1 => 'Activado'
];
$roles = Role::select('name')->whereNotNull('name')->groupBy('name')->orderBy('name')->get();
$rolesData = [];
if ($roles) {
foreach ($roles as $role) {
$rolesData[] = $role->name;
}
}
return response()->json(['statuses' => $statuses, 'roles' => $rolesData]);
}
public function paginated () {
$rowsPerPage = request('rowsPerPage');
$users = User::filtered();
return response()->json($users->paginate($rowsPerPage != 'undefined' ? $rowsPerPage : 10));
}
public function allFiltered () {
$users = User::filtered(false);
return response()->json($users->get());
}
}
<?php
Route::group(['prefix' => 'users'], function () {
Route::get('/paginated', 'UserController@paginated');
Route::get('/filters', 'UserController@filters');
Route::get('/all-filtered', 'UserController@allFiltered');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment