Last active
June 16, 2023 21:50
-
-
Save nklatt/0e4bc8d39b7ae4c9cddb723b4d082b41 to your computer and use it in GitHub Desktop.
Laravel Backpack CRUD entry list filtering based on related rows
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Controllers\Admin; | |
use Backpack\CRUD\app\Http\Controllers\CrudController; | |
class AccountCrudController extends CrudController | |
{ | |
use \Backpack\CRUD\app\Http\Controllers\Operations\ListOperation; | |
protected function setupListOperation() | |
{ | |
$that = $this; | |
$filterSetup = function($value = null) use($that) { | |
if (!empty($_GET)) { | |
// change from 'select * from...' to 'select accounts.* from...' | |
$this->crud->query->select('accounts.*'); | |
// pull in data needed for season filter | |
// if you need data for accounts that don't have joined data, use leftJoin instead of join | |
$this->crud->query->join('account_person', 'account_person.account_id', '=', 'accounts.id'); | |
$this->crud->query->join('people', 'people.id', '=', 'account_person.person_id'); | |
$this->crud->query->join('registrations', 'registrations.person_id', '=', 'people.id'); | |
$this->crud->query->join('programs', 'programs.id', '=', 'registrations.program_id'); | |
// get rid of the extraneous rows due to the joins | |
$this->crud->query->groupBy('accounts.id'); | |
} | |
}; | |
$this->crud->addFilter( | |
array( | |
'name' => 'filters_setup', | |
'type' => 'hidden', | |
), | |
false, | |
$filterSetup, // called if the filter is active (which it shoulnd't be since it's hidden) | |
$filterSetup // called if the filter is not active | |
); | |
$this->crud->addFilter( | |
array( | |
'name' => 'season', | |
'type' => 'dropdown', | |
'label' => 'Season', | |
), | |
\App\Models\Season::getSeasonList(), // get seasons as an array of id => name | |
function($value) { | |
$this->crud->query->where(function($query) use($value) { | |
$this->crud->query->where('programs.season_id', '=', $value); | |
}); | |
} | |
); | |
// other filters and columns for display here... | |
} | |
// other CRUD code here... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment