Laravel search multiple fields - laravel

I currently have a search function on my website, I need it to search 3 fields - appid, mobilenumber, email .
Right now once the user enters the data in the search box it searches all 3 but its not working.
Data is collected using GET.
Here is my query
http://www.example.com?id=1&searchall=07853637362
$mobile = INPUT::get('searchall');
$email = INPUT::get('searchall');
$appid = INPUT::get('searchall');
$data = DB::table('leads')
->when($mobile, function($query) use ($mobile){
return $query->where('MobilePhone', $mobile);
})
->when($email, function($query) use ($email){
return $query->where('Email', $email);
})
->when($appid, function($query) use ($appid){
return $query->where('AppID', $appid);
})
->get();
So I need it to search each field until it finds the correct field value.

$mobile = INPUT::get('searchall');
$email = INPUT::get('searchall');
$appid = INPUT::get('searchall');
$data = DB::table('leads')
->when($mobile, function($query) use ($mobile){
return $query->orWhere('MobilePhone', $mobile);
})
->when($email, function($query) use ($email){
return $query->orWhere('Email', $email);
})
->when($appid, function($query) use ($appid){
return $query->orWhere('AppID', $appid);
})->get();

To search data try with like
->when($mobile, function($query) use ($mobile){
return $query->where('MobilePhone', 'like', '%'. $mobile . '%');
})
to actually search each field, use orWhere
$keywords = Input::get('searchall');
$data = DB::table('leads')
->where('mobilephone', '=', $keywords)
->orWhere('email', '=', $keywords)
->orWhere('AppID', '=', $keywords)
->get();

I don't understand why you need the same value from the user using 3 variables, so the following is the simplified version:
$searched = Input::get('searchall');
$matched = DB::table('leads')
->where('MobilePhone', $searched)
->orWhere('Email', $searched)
->orWhere('AppID', $searched)
->get();

Related

Laravel 8 - How to use where conditions for relation's column

hello friends can you help me to get the contents of $filter? I want to run where which is where the target column is in the relation array
$filter = $request->get('Biogear');
$data = DetailBarang::with(['barang' => function ($q) use ($filter) {
$q->where('brand', '=', $filter);
}])->get();
return response()->json($data);
you can try this
$filter = $request->get('Biogear');
$data = DetailBarang::with('barang')->whereHas('barang',function (Illuminate\Database\Eloquent\Builder $q) use ($filter) {
$q->where('brand', '=', $filter);
})->get();
return response()->json($data);

Laravel with where like condition in relationship

I have a WorkPackage model with below relationship.
public function work_items()
{
return $this->hasMany(WorkItem::class);
}
And WorkPackage has 'title','project_id' columns and work_items has 'title','work_package_id' columns. Now I want to search user typed keyword is matching with title in both table.
Here is my tried function
public function getWorkPackageProposals($projectId, $title)
{
$result['data'] = $this->workPackage->with(['work_items' => function ($query) {
$query->where('title', 'LIKE', "%{$title}%");
}])
->where('project_id', $projectId)
->where('title', 'LIKE', "%{$title}%")
->get();
return $result;
}
but its not working.
Please find the below code for I used to create object of WorkPackage.
public function __construct(WorkPackage $workPackage)
{
$this->workPackage = $workPackage;
$this->setModel(WorkPackage::class);
$this->workItemRepository = app(WorkItemRepository::class);
}
whereHas() works to specify additional filters for the related model to check :
$result['data'] = $this->workPackage->whereHas('work_items', function ($query) use ($title) {
$query->where('title', 'LIKE', "%{$title}%");
})
->where('project_id', $projectId)
->where('title', 'LIKE', "%{$title}%")
->get();
return $result;
Below code works for me. Thanks to everyone for help to get right answer.
$result['data'] = $this->workPackage->with(['work_items' => function ($q) use ($title) {
$q->where('title', 'LIKE', "%{$title}%");
}])
->where('project_id', $projectId)
->where('title', 'LIKE', "%{$title}%")
->get();
return $result;
I think your problem will be solved with join method:
$result = $this->workPackage
->join('work_items', 'work_packages.id', '=', 'work_items.package_id')
->where('work_items.title', 'LIKE', '%{$term}%')
->orWhere('work_packages.title', 'LIKE', '%{$term}%')
->get();

Laravel dynamic query

I have a GET form with three filters.
make
Year
country
I need to get all posts from db. But filter the results based on these three filters.
If a country is selected, get posts for that country only or all countries.
if a make is selected, get posts for that make only or all makes
if a year is selected, get posts for that year only or all years
how to write one query that filters all these three options. What I have done is used if and else statements and written different queries for each scenario. That's 9 queries to get one information. Can we make it dynamic and just have one query?
My Example query:
public function search(Request $request)
{
$search=$request->input('search');
if($request->input('country') == "all")
{
$posts = Post::where('status','Published')->orderBy('status_change','DESC')
->where('status','Published')
->where(function($query) use ($search){
$query->where('title','LIKE','%'.$search.'%');
$query->orWhere('model','LIKE','%'.$search.'%');
$query->orWhere('notes','LIKE','%'.$search.'%');
$query->orWhere('description','LIKE','%'.$search.'%');
})
->paginate(25);
}
else
{
$posts = Country::where('country_name', $request->input('country'))->first()->posts()->orderBy('status_change','DESC')
->where('status','Published')
->where(function($query) use ($search){
$query->where('title','LIKE','%'.$search.'%');
$query->orWhere('model','LIKE','%'.$search.'%');
$query->orWhere('notes','LIKE','%'.$search.'%');
$query->orWhere('description','LIKE','%'.$search.'%');
})
->paginate(25);
}
return view('welcome')
->with('published_posts',$posts)
;
}
I think something like this would work:
/**
* #param Request $request
*/
function search(Request $request)
{
$postsQuery = Post::where('status', 'Published');
if ($request->has('country')) {
$country = $request->country;
// assuming relationships are setup correclty
$postsQuery->whereHas('country', function ($query) use ($country) {
$query->where('country_name', 'LIKE', $country);
});
}
if ($request->has('search')) {
$postsQuery->where(function ($query) use ($search) {
$query->where('title', 'LIKE', '%' . $request->search . '%');
$query->orWhere('model', 'LIKE', '%' . $request->search . '%');
$query->orWhere('notes', 'LIKE', '%' . $request->search . '%');
$query->orWhere('description', 'LIKE', '%' . $request->search . '%');
});
}
$postsQuery->orderBy('status_change', 'DESC')->paginate(25);
return view('welcome')->with('published_posts', $result);
}
I used 'when' method.
$make = null;
$year = null;
$country = null;
if($request->filled('make')){
$make = $request->query('make');
}
if($request->filled('year')){
$year = $request->query('year');
}
if($request->filled('country')){
$country = $request->query('country');
}
$posts = DB::table('posts')
->when($make, function($query, $make){
return $query->where("make", "=", $make);
})
->when($year, function($query, $year){
return $query->whereYear("year", "=", $year);
})
->when($country, function($query, $country){
return $query->where('country', "like", $country);
})
->get();
Check out the Laravel Docs:
Check out an article here

or where clause - Laravel eloquent

I have this query:
if($keyword){
array_push($where, ['name_en', 'LIKE', '%'.$keyword.'%']);
}
The problem is that I have and name_fr column and I need to use OR clause - array_push($where, ['name_fr', 'LIKE', '%'.$keyword.'%']).
I can't use ->orWhere, because I have many dynamic search fields - they may exists or not.
For the example:
if($fromPrice){
array_push($where, ['price', '>=', $fromPrice]);
}
if($toPrice){
array_push($where, ['price', '<=', $toPrice]);
}
And the query is:
$cars= Property::with(array(
'photos'=>function($query){
$query->select(['car_id', 'name']);
}
))->where($where)->paginate(10);
I need to select WHERE name_en LIKE %val% OR name_fr LIKE %val% with another queries.
Is there a way to use somehow where, 'OR' and LIKE in the above way including another values from $where array ?
to achieve that a suggest you to divide your query as below and don't put your keyword condition within $where array:
$query = Property::with(array(
'photos'=>function($query){
$query->select(['car_id', 'name']);
}
))->where($where);
if($keyword){
$query = $query->where(function ($query) use ($keyword) {
$query->where('name_fr', 'like', $keyword)
->orWhere('name_en', 'like', $keyword);
});
}
$cars = $query->paginate(10);
You can also go with
$propertyQuery = Property::query();
if($keyword){
$propertyQuery->where(function($query) use ($keyword){
$query->where('name_fr', 'LIKE', '%'.$keyword.'%')->orWhere('name_en', 'LIKE', '%'.$keyword.'%');
});
}
$cars = $propertyQuery->paginate(10);

How can I Refactor this search filter query?

I need to search in multiple tables. I'm checking every single request object. For example: I am checking if the request has that object then concating it to my main query and getting that query result at the last. It doesn't looks and isn't good. How can I make this search query filter better in laravel?
Note: I have searched questions in stackoverflow but they are dealing with only one model.
$query = DB::table('clients')
->leftjoin('ecommerce_contacts','ecommerce_contacts.client_id', '=', 'clients.id')
->select('ecommerce_contacts.*', 'clients.*')
->where('clients.is_deleted', '=', '0');
if(!is_null($request->fname)){
$query+=->where('clients.fname', 'like', '%$request->fname%');
}
if(!is_null($request->lname)){
$query+=->where('clients.lname', 'like', '%$request->lname%');
}
if(!is_null($request->gender)){
$query+=->where('clients.sex', $request->sex);
}
if(!is_null($request->number)){
$query+=->where('ecommerce_contacts.sex', 'like', $request->number);
}
if(!is_null($request->registered_date)){
}
if(!is_null($request->purchase)){
}
$client = $query->get();
$data = json_encode($clients);
return $data;
Use conditional clauses:
DB::table('clients')
->leftjoin('ecommerce_contacts','ecommerce_contacts.client_id', '=', 'clients.id')
->select('ecommerce_contacts.*', 'clients.*')
->where('clients.is_deleted', '=', '0')
->when(request()->has('fname'), function ($query) {
return $query->where('clients.fname', 'like', '%' . request()->fname . '%');
})
->when(request()->has('lname'), function ($query) {
return $query->where('clients.lname', 'like', '%' . request()->lname . '%');
})
->when(request()->has('gender'), function ($query) {
return $query->where('clients.sex', '=', request()->gender);
})
...
$query=DB::table('clients')
->leftjoin('ecommerce_contacts','ecommerce_contacts.client_id', '=', 'clients.id')
->select('ecommerce_contacts.*', 'clients.*')
->where('clients.is_deleted', '=', '0');
$search_fields=['fname','lname','gender','number','registered_date','purchase'];
foreach($search_fields as $key){
if(!is_null($key)){
$query->orWhere('clients.'.$key, 'LIKE', '"%" . '.$request->$key.' . "%"');
}
}
$client = $query->get();
$data = json_encode($client);
return $data;
I upvoted #DigitalDrifter 's answer because i liked it but I prefer my filter pattern.
Have a look at this:
$query = DB::table('clients')
->leftjoin('ecommerce_contacts','ecommerce_contacts.client_id', '=', 'clients.id')
->select('ecommerce_contacts.*', 'clients.*')
->where('clients.is_deleted', '=', '0');
!isset($request->fname) ?: $query->where('clients.fname', 'like', '%$request->fname%');
!isset($request->lname) ?: $query->where('clients.lname', 'like', '%$request->lname%');
!isset($request->gender) ?: $query->where('clients.sex', $request->sex);
!isset($request->number) ?: $query->where('ecommerce_contacts.sex', 'like', $request->number);
$client = $query->get();
$data = json_encode($clients);
return $data;
I think this is more readable and requires less line of code.

Resources