As I see, there are any of columns you search through inside your Client model. So query results are the same.
'orWhere' not work eloquent model relationship
- Laravel Version: 5.7.25
- PHP Version: 7.2.14
- Database Driver & Version: MySQL 2ª gen. 5.7
We are working to do a search in Ajax. something goes wrong in the relationship between the models. when a user searches for his customers he should see his. but with the orWhere function it seems that laravel forgets the relationship.
and they want to tell me not to open support on github? if this is not a bug. so what is it?
CODE:
$finder = Auth::user()->client()
->where('business_name', 'LIKE', '%' . $query . '%')
->orWhere('vat_number', 'LIKE', '%' . $query . '%')
->orWhere('fiscal_code', 'LIKE', '%' . $query . '%');
var_dump(Auth::id());
dd($finder->get());
this code returns the same result for two types of different users:
int(971501)
Collection {#1019 ▼
#items: array:2 [▼
0 => Client {#1022 ▼
#connection: "mysql"
#table: "clients"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:24 [▼
"id" => 895527
"user_id" => 971500
"company_id" => 776888
"type" => "3"
"target_code" => "WSOPGP"
"mobile" => "+39"
"fax" => null
"cap" => "06073"
"common" => "Corciano"
"province" => "PG"
"nation" => "IT"
"note" => null
"site" => null
"profile_picture" => "/assets/img/brand/company.png"
"cover_image" => null
"created_at" => "2019-02-18 17:53:07"
"updated_at" => "2019-02-18 17:53:07"
]
#original: array:24 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
#guarded: array:1 [▶]
}
1 => Client {#1023 ▶}
]
}
as you see inserted is not the same even if we are sure to write report via ID authentication
You always need to pay attention to the resulting query whenever you use orWhere. In this case, you should wrap the wheres in a Closure to effectively wrap those conditions in parentheses
$finder = Auth::user()->client()
->where(function ($query) {
$query->where('business_name', 'LIKE', '%' . $query . '%')
->orWhere('vat_number', 'LIKE', '%' . $query . '%')
->orWhere('fiscal_code', 'LIKE', '%' . $query . '%');
});
Resulting in:
SELECT
*
FROM
`clients`
WHERE
`clients`.`user_id` = ?
AND `clients`.`user_id` IS NOT NULL
AND (
`business_name` LIKE ?
OR `vat_number` LIKE ?
OR `fiscal_code` LIKE ?
)
Please or to participate in this conversation.