Skip to content

Instantly share code, notes, and snippets.

@PoTHuYJoHN
Last active January 15, 2016 12:54
Show Gist options
  • Save PoTHuYJoHN/9ba4aa3d87c68b3f8b49 to your computer and use it in GitHub Desktop.
Save PoTHuYJoHN/9ba4aa3d87c68b3f8b49 to your computer and use it in GitHub Desktop.
Search threads using whereHas and orWhereHas

This example provides functionality of searching records through multiple relations.

Here is used "whereHas" and "orWhereHas" functionality.

To make search with nested boolean expressions here is used hack with $query->where( here goes whereHas and orWhere)

Example based on package https://github.com/cmgmyr/laravel-messenger

<?php
$q = 'someFirstNameOrLastNameOrCompany';
$limit = 20;
$threads = Thread::latest('updated_at')
->whereHas('participants', function($query) use($q) {
$query->whereHas('user', function($query) use($q) {
//search connected two tables if any of them has record appropriate to $q
$query->where(function($subQuery) use($q) {
$subQuery->whereHas('personalContacts', function($query) use($q) {
$query->whereRaw('(firstName LIKE ? OR lastName LIKE ? OR company LIKE ?)',
['%'.$q.'%', '%'.$q.'%', '%'.$q.'%']);
;
})
->orWhereHas('companyContacts', function($query) use($q) {
$query->whereRaw('(firstName LIKE ? OR lastName LIKE ? OR company LIKE ?)',
['%'.$q.'%', '%'.$q.'%', '%'.$q.'%']);
;
});
})
;
});
})
->forUser($userId)
->with(['participants' => function($query) {
$query->with(['user' => function($q) {
$q->with(['personalContacts' => function($q){
$q->with('avatar');
}, 'companyContacts' => function($q){
$q->with('avatar');
}]);
}, 'user.avatar']);
}])
->paginate($limit)
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment