Laravel: Using multiple search terms to get an entry - php

Right now, I am grabbing users who fit a certain criteria like this:
$searchTerm = 'MULTI';
$multiUser = USER::where('code', 'LIKE', '%'.$searchTerm.'%')->get();
Now I changed the code to be "MANY" but we have a lot of users who already have MULTI as their code so I need the searchTerm to grab both. Can I do this in one query?

User::query()
->where('code', 'LIKE', '%MULTI%')
->orWhere('code', 'LIKE', '%MANY%')
->get();

Related

Laravel 9 - Eloquent group results of query

I am looking for a way to take one query in Eloquent to get all search results, and then take those results, group them by type, and output the different types.
I currently have this setup to get all my search results:
$listings = Listing::where('listings.expiration_date', $date_operator, date('Y-m-d H:i:s'));
$listing->where(function($query) use ($keyword) {
$query->where('listings.lot_number', 'LIKE', '%'.$keyword.'%')
->orWhere('listings.title', 'LIKE', '%'.$keyword.'%')
->orWhere('listings.brand', 'LIKE', '%'.$keyword.'%')
->orWhere('listings.grade', 'LIKE', '%'.$keyword.'%')
->orWhere('listings.tags', 'LIKE', '%'.$keyword.'%')
->orWhere('listings.player', 'LIKE', '%'.$keyword.'%');
})->leftJoin('bids', function($join){
$join->on('bids.listing_id', '=', 'listings.id')
->on('bids.id', '=', DB::raw("(select max(id) from bids WHERE bids.listing_id = listings.id)"));
})->leftJoin('media', function($join) {
$join->on('media.listing_id', '=', 'listings.lot_number')
->where('media.group_order', '=', '1')->groupBy('media.group');
});
$listings = $listings->get();
The resulting $listings shows all the search results that I want to appear. Each listing has a specific type (item_type) assigned to them (i.e. Card, Ball, Bat, etc). I'd like to take all those results and group the types so that I can get a unique list of types to display in the menu. I've tried GroupBy on the Collection but that doesn't seem to be working.
Thank You
Use the power of collections
$itemTypes = $listings->pluck('item_type')->unique()
// if item type is a sub array / relationship then you will need to use dot notation
So we are plucking only the 'item_type' field, removing all duplicates by using the unique method and you should then have a collection of unique item_type's

Laravel - Query Model if values contain a certain string (taken from search input)

I am implementing a search using Laravel and Ajax. So I have a Product which belongs to a Tag and a Subcategory. On the other hand the Subcategory belongs to a Category. I want to check all of their properties (field values) and check if they contain the given string. With some searching I found out that I have to use LIKE. Here is what I tried:
$products = Product::where('name_en', 'LIKE', $search)->get();
However this will get the products if the search string matches exactly the value. I want to match if it contains it. How can I proceed with the belongsTo relationships? How can I check the propreties of Tag and Subcategory as well? How to chain everything together so I achieve the desired result? Thanks in advance.
you are doing one thing wrong, your query returns you exact matches because you given the exact string. But your query should be like this.
$products = Product::where('name_en', 'LIKE', '%'.$search.'%')->get();
Above query will gives your products which contains the searched string.
And if you want to search in relational tables then you can user laravel method join(). But there are one more method whereHas but I always avoiding this method, because it creates very complex query. which is very heavy. So you can use join() method which will add inner join with relational table.
Here is the example of join:
$products = Product::join('tags', function($builder) {
$builder->on('tags.id', '=', 'products.tag_id');
// here you can add more conditions on tags table.
})
join('sub_categories', function($builder) {
$builder->on('sub_categories.id', '=', 'products.tag_id');
// here you can add more conditions on subcategories table.
})
->where('name_en', 'LIKE', '%'.$search.'%')
->get();
This is the basic example, you can use this according to your requirement.
To add to Lakhwinder Singh’s answer, it might be worth wrapping it up in a scope that you can apply to your model:
class Product extends Model
{
public function scopeSearch($query, $keywords)
{
return $query->where('name_en', 'LIKE', '%'.$keywords.'%');
}
}
You can then use this scope like this:
$products = Product::search($keywords)->get();
Which means you don’t have to keep manually adding “LIKE” conditions throughout your application.
As an aside, Laravel’s introducing Scout, a driver-based full text search extension for Eloquent, in version 5.3.
What you want is to write an advanced query to search product based on related models too, so as previous suggestion by others, you have to write join statements.
Check my example code below, which is written to search members, the search string also will bring members if the string matches, members skills or positions, so this will surely help you.
$users = User::select('app_users.*')
->distinct()
->join('app_members', 'app_users.id', '=', 'app_members.app_users_id')
->leftJoin('app_members_jobtitles', 'app_members.id', '=', 'app_members_jobtitles.app_members_id')
->leftJoin('app_jobtitles', 'app_members_jobtitles.app_jobtitles_id', '=', 'app_jobtitles.id')
->leftJoin('app_members_tags', 'app_members.id', '=', 'app_members_tags.app_members_id')
->leftJoin('app_technologies', 'app_members_tags.app_technologies_id', '=', 'app_technologies.id')
->whereNull('app_users.activation')
->where('app_users.block','=',0)
->where(function ($query)use ($search) {
$query->orWhere('app_users.first_name', 'like', '%'.$search.'%')
->orWhere('app_users.last_name', 'like', '%'.$search.'%')
->orWhere('app_members.company', 'like', '%'.$search.'%')
->orWhere('app_members.job_title', 'like', '%'.$search.'%')
->orWhere('app_jobtitles.title', 'like', '%'.$search.'%')
->orWhere('app_technologies.title', 'like', '%'.$search.'%')
->orWhere('app_members.summary', 'like', '%'.$search.'%');
})
->get();
Note the following join in the above code, which is in your case category and sub category
->leftJoin('app_members_jobtitles', 'app_members.id', '=', 'app_members_jobtitles.app_members_id')
->leftJoin('app_jobtitles', 'app_members_jobtitles.app_jobtitles_id', '=', 'app_jobtitles.id')

Laravel Eloquent Search Multiple Related Tables

I am struggling with figuring out how to run a like query against multiple related tables.
I have a submissions table that has related users, mcd_forms, and submission_statuses tables.
Here is my code for running a LIKE statement with the given $terms_like.
$submission = new Submission;
$terms_like = '%'.$search_terms.'%';
$data['submissions'] = $submission
->join('users as users', 'users.id', '=', 'submissions.user_id')
->join('mcd_forms as forms', 'forms.submission_id', '=', 'submissions.id')
->join('submission_statuses as statuses', 'statuses.id', '=', 'submissions.submission_status_id')
->where(function($q) use ($terms_like) {
$q->where('users.user_group_id', '=', Auth::user()->user_group_id)
->orWhere('forms.name', 'like', $terms_like)
->orWhere('forms.custom_id', 'like', $terms_like)
->orWhere('forms.start_date', 'like', $terms_like)
->orWhere('forms.end_date', 'like', $terms_like)
->orWhere('forms.soft_sell_date', 'like', $terms_like)
->orWhere('forms.region', 'like', $terms_like)
->orWhere('statuses.status_formatted', 'like', $terms_like);
});
No matter what I try it returns incorrect results. What am I doing wrong?
In your query above, since you are not using the "%" symbol, your like clause is working as an "=" since it's trying to match the whole word.
Replace all the "where" clause like this:
->orWhere('forms.name', 'like', "%".$terms_like."%")
This will try to match the word anywhere in the text.
You can try 'like' operator following this:
$users = DB::table('users')
->where('forms.name','LIKE', '%'.$terms_like.'%')
->get();

Query for multiple fields with Laravel

So I am trying to create a search functionality so that you can query for both first and last name. What can I use as an AND statement for the query?
public function find()
{
$search = Input::get('contact_search');
$query = Contact::orderBy('name', 'desc');
if (is_null($search))
{
$contacts = $query->paginate(15);
//return View::make('contacts.index')->with(array('contacts' => $contacts));
} else {
$contacts = $query->where('firstName', 'LIKE', "%{$search}%")
->orWhere('lastName', 'LIKE', "%{$search}%")
->paginate(15);
$contact = Contact::find(1);
}
return View::make('hello')->with(array('contacts' => $contacts));
}
I have tried
$query->where('firstName', 'LIKE', "%{$search}%")
->Where('lastName', 'LIKE', "%{$search}%")
but that does not work either. Any advice would be awesome! Thanks.
where() acts as an and statement already. Just chain them together.
$people = People::where('first_name','=','John')->where('last_name','=','Doe')->get();
In your query, you have ->Where. Make sure its lowercase.
Also, your method could use some optimization. You are searching for multiple contacts and paginating the results, but then you are doing a find(1) for some reason. A better approach is to just do the following:
$contact = Contact::orderBy('name','desc')
->where('firstName', 'LIKE', "%{$search}%")
->where('lastName', 'LIKE', "%{$search}%")
->first();
That will return your first contact in the results. No need for pagination. And find() actually searches for records based off of id's anyways so you don't want to use that in this case.
If you use where it will add AND if you use multiple where. However I don't know if in your case you want to use AND because you if someone will put into form Jo you will search for poeple that hat Jo both in name and surname, so for example John Smith won't be found here because his surname doesn't contain Jo.
So answering your question you could use:
$contacts = $query->where('firstName', 'LIKE', "%{$search}%")
->where('lastName', 'LIKE', "%{$search}%")
->paginate(15);
but probably this won't make much sense.
It's hard to also say what exactly you do here, because you have here:
$contacts = $query->where('firstName', 'LIKE', "%{$search}%")
->orWhere('lastName', 'LIKE', "%{$search}%")
->paginate(15);
$contact = Contact::find(1);
using those 2 lines first you look for people who have $search in first or last name and paginate them, and when using Contact::find(1); you find person with id 1. It also doesn't seem to be good solution to anything here.
If you would like to find the first record that have $search either in first or last name, you should use:
$contacts = $query->where('firstName', 'LIKE', "%{$search}%")
->where('lastName', 'LIKE', "%{$search}%")
->first();
without orWhere and without paginate.

Searching Multiple Rows in database

Hello everyone I have ran into a small problem i need to know how to be able to search multiple rows in my database and i am having some difficulty with my code can you please take a look at my query
$raw_results = DB::table('students')->select('Name', 'Date' ,'Class')->where('Name', 'LIKE', "%$query%")->get();
Try using orWhere() as part of your query to add additional constraints.
$rawResults = DB::table('students')
->select('Name', 'Date', 'Class')
->where('Name', 'LIKE', "%{$query}%")
->orWhere('Class', 'LIKE', "%{$query}%")
->get();

Categories