如何在Eloquent中编写AND条件?将orWhere替换为等效AND逻辑
orWhere with where for AND Logic Got it, let's adjust your query to use AND logic instead of OR. The fix is straightforward since Laravel's where method uses AND as the default logical operator between conditions.
Original Code (OR Logic)
$jobs = Jobs::where('location','like', '%' . $request->location .'%') ->orWhere('category', 'like', '%' . $request->category . '%') ->get();
Modified Code (AND Logic)
Simply swap out orWhere with where—this will ensure both the location and category conditions must be satisfied:
$jobs = Jobs::where('location','like', '%' . $request->location .'%') ->where('category', 'like', '%' . $request->category . '%') ->get();
Why This Works
Laravel chains where clauses with AND by default, so this query will return only jobs where:
- The
locationfield contains the value from$request->location(via thelikewildcard match)
AND - The
categoryfield contains the value from$request->category
This matches exactly what you're looking for with an equivalent of andWhere (note: Laravel doesn't have an andWhere method because where already handles AND logic).
Bonus: Robustness Improvement
If there's a chance $request->location or $request->category might be empty, add checks to avoid unnecessary wildcard matches (which could return all records):
// Start with a base query $query = Jobs::query(); // Add location condition only if the parameter is filled if ($request->filled('location')) { $query->where('location', 'like', '%' . $request->location . '%'); } // Add category condition only if the parameter is filled if ($request->filled('category')) { $query->where('category', 'like', '%' . $request->category . '%'); } // Execute the query $jobs = $query->get();
内容的提问来源于stack exchange,提问作者Fariha Nuzhat Majumdar

