Hello guys i need to implement filtering result for Document model. My document model have relation with Customer and i need to filter that results with searching multiple columns in customer relation (name and address). I try with traditional way $document->customerRelation->name
, customer.name
and isn't working.
So i have HTML table with prited documents and there is also printed customer name and customer address. When i type in text box some keywords like (jon or test) i need to filter that columns.
Document | Customer | Address | Document Type |
---|---|---|---|
00213 | Jon | Test | Inovice |
00214 | Thomas | Test | Proforma |
00215 | Agly | Test | Guaranty |
00216 | Adams | Test | User manual |
Here is code
public function index(Request $request)
{
$documents =
Document::when(
$request->has('document_tip_id'), function ($q) use ($request) {
return $q->where('document_tip_id', $request->query('document_tip_id'));
}) // this working
// Here i need to filter by relation (customer.name or address and other columns)
->when(
$request->has('keywords'), function ($q) use ($request) {
return $q->where('customer.name', '%'.$request->query('customer') . '%');
})
->with('products')
->with('customer')
->orderBy('created_at');
$documents = $documents->paginate(20)->withQueryString();
dd($documents);
return ....
}
Dump
Illuminate\Pagination\LengthAwarePaginator {#408 ▼ // app/Http/Controllers/Order/BuyerController.php:38
#items: Illuminate\Database\Eloquent\Collection {#346 ▼
#items: array:20 [▼
0 => App\Models\Document {#321 ▼
#connection: "mysql"
#table: "dokument"
#primaryKey: "id"
#keyType: "int"
#observables: []
#relations: array:2 [▼
"product" => Illuminate\Database\Eloquent\Collection {#343 ▶}
"customer" => App\Models\Customer {#432 ▼
#connection: "mysql"
#table: "customer"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
+preventsLazyLoading: false
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#escapeWhenCastingToString: false
#attributes: array:28 [▼
"id" => 975
"code" => "123"
"name" => "Jon Don"
"address" => "Test address"
"created_at" => "2020-11-05 21:55:46"
"updated_at" => "2020-11-05 21:55:46"
"deleted_at" => null
]
Model
// Customer.php
public function customer()
{
return $this->belongsTo(Customer::class, 'subjekat_id');
}
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'customer.name' in 'where clause'