crud
crud copied to clipboard
To be able to filter/search by foreign table's field
Hi,
I would like to propose being able to write code like below:
TD::make('payment_gateway_id', 'Payment Gateway')
->sort()
->query(function ($search, $builder) {
return $builder
->select('customers.*') // required, otherwise sorting has issues
->join('payment_gateways', 'payment_gateways.id', '=', 'payment_gateway_id')
->where('payment_gateways.name', 'like', '%' . $search. '%');
})
->render(function ($model) {
return $model->payment_gateway->name;
})
The purpose is so that we can search for a foreign table's field e.g. name instead of only being able to filter by ID as the user might not know the ID.
I was able to modify ResourceRequest.php
with the code below,
// update in ResourceRequest.php
public function getModelPaginationList()
{
$builder = $this->model()
->with($this->resource()->with())
->filters()
->filtersApply($this->resource()->filters());
foreach (collect($this->resource()->columns()) as $column) {
$callback = $column->queryClosure; // also need to modify TD.php to support queryClosure
if (!is_null($callback)) {
$filters = $this->request->all('filter');
$key = $column->column;
if (Arr::exists($filters, $key)) {
$term = $filters[$key];
$builder = $callback($term, $builder);
}
}
}
return $builder->paginate($this->resource()->perPage());
}
// add to TD.php
/**
* @var Closure|null
*/
public $queryClosure;
public function query(Closure $queryClosure)
{
$this->queryClosure = $queryClosure;
return $this;
}
Is there a better approach to make searching by foreign table field easier?
@tabuna able to let me know? My code is starting to rely on this and I would like such functionality to be in the main crud repo. Thank you.