Searching with Laravel or_where() - php

My goal is to search for a first and last name using Laravel. As the code is written, it searches for a First Name or Last Name, what I would like to do is get it to search for both First Name and Last Name. How would I accomplish this?
PHP - Search Statement
public function search($search_input) {
$response = DB::table(self::$table)
->select(array(
'ID',
'User_ID',
'Signup_Date',
'First_Name',
'Last_Name',
DB::raw('CONCAT(First_Name," ",Last_Name) AS Name')
))
->where('First_Name', 'LIKE', '%'.$search_input.'%')
->or_where('Last_Name', 'LIKE', '%'.$search_input.'%')
->where_not_null('User_ID')
->order_by('Signup_Date', 'desc')
->get();
return $response;
}
EDIT: I forgot to include we are using Laravel 3. https://laravel3.veliovgroup.com/docs/database/fluent

As I understand, your query condition is
(First_Name LIKE "%xx%" OR Last_name LIKE "%xx%") AND User_id IS NOT NULL
You should modify your query as below to use nested where clauses:
public function search($search_input) {
$response = DB::table(self::$table)
->select(array(
'ID',
'User_ID',
'Signup_Date',
'First_Name',
'Last_Name',
DB::raw('CONCAT(First_Name," ",Last_Name) AS Name')
))
->where(function($query) use ($search_input) {
$query->where('First_Name', 'LIKE', '%'.$search_input.'%')
->or_where('Last_Name', 'LIKE', '%'.$search_input.'%');
}
->where_not_null('User_ID')
->order_by('Signup_Date', 'desc')
->get();
return $response;
}

If you have it search both first name and last name, then I doubt it would return results. Because it would imply the search query would have to match a record where the input is like the first name and like the last name. I think what you are actually after is more of a compound search. As you have the selects in your query, you might be able to do the following instead.
public function search($search_input) {
$response = DB::table(self::$table)
->select(array(
'ID',
'User_ID',
'Signup_Date',
'First_Name',
'Last_Name',
DB::raw('CONCAT(First_Name," ",Last_Name) AS Name')
))
->where('Name', 'LIKE', '%'.$search_input.'%')
->where_not_null('User_ID')
->order_by('Signup_Date', 'desc')
->get();
return $response;
}
This should work because Name is being set by the CONCAT function.

Related

How can I search with multiple columns in Laravel

I am very new in Laravel, I try to search with one column and this is my code. But now I want to search with multiple columns - how can I do that?
My controller :
public function search_pers(Request $request)
{
$mle = $request->input('mle');
$listpers = Personne::where('mle', 'LIKE', '%'.$mle.'%')->get();
return view('frontend.etat_civil', ['personnes' => $listpers]);
}
You could use an array
Personne::where([
['col1', '=', 'value1'],
['col2', '<>', 'value2'],
[Your_col, OPERATOR, value],
...
])
or in your case
$str = "concat('%',".$mle .",'%')";
$listpers = Personne::where([
['mle', 'LIKE', $str],
['col1', '=', 'value1'],
['col2', '<>', 'value2'],
[Your_col, OPERATOR, value],
)->get();
As I understand what you need is an orWhere condition:
public function search_pers(Request $request)
{
$mle = $request->input('mle');
$listpers = Personne::where('mle', 'LIKE', '%'.$mle.'%')->orWhere('nom','like','%'.$mle.'%')->get();
return view('frontend.etat_civil', ['personnes' => $listpers]);
}
Another alternative and probably a better one is to use fulltext search.
MySQL Fulltext search

How can i find only deleted rows in Laravel?

I'm using SoftDeletesin my projects, which is recognized as deleted_at in database table, I want to search and find only deleted rows.
Here is my controller code
public function trashedJobSearch(Request $request)
{
$search = $request->get('search');
$jobs = Jobs::select('id', 'company_name', 'position_name', 'job_description','deleted_at', 'created_at', 'expire_date', 'status')
->where(DB::raw('lower(company_name)'), 'like', '%' . mb_strtolower($search) . '%')
->orWhere(DB::raw('lower(position_name)'), 'like', '%' . mb_strtolower($search) . '%')
->where('deleted_at', '!=', null)
->paginate(10);
return view('/trashed', compact('jobs'));
}
I tried to use onlyTrashed() but it's not working either.
As you have orWhere you need to use a grouping and also onlyTrashed
Jobs::select('id', 'company_name', 'position_name', 'job_description','deleted_at', 'created_at', 'expire_date', 'status')
->where(function ($query) use ($search) {
$query->where(DB::raw('lower(company_name)'), 'like', '%' . mb_strtolower($search) . '%')
->orWhere(DB::raw('lower(position_name)'), 'like', '%' . mb_strtolower($search) . '%');
})->onlyTrashed()
->paginate(10);
The onlyTrashed() method should work for you. Docs for Laravel deleted entries. I have seen times where adding the raw select statement screws it up though.
Take out the extra bits with the select and DB::raw and then add them in after you have what you need. Start with the simplest:
$testOfDeletedOnlyJobs = Jobs::onlyTrashed()->get();
From here, add in the other parts of your query to see where and why it fails. If the above gives you nothing, perhaps there are no deleted records?
You can use
Model::onlyTrashed()->get();
Did you have looking for this post yet?
How to get all rows (soft deleted too) from a table in Laravel?
You can try this.
In your Model-
use Illuminate\Database\Eloquent\SoftDeletes;
class ModelName extends Model
{
use SoftDeletes;
}
To get only deleted rows
$search = $request->get('search');
$data = App\ModelName::onlyTrashed()
->where('id', $search)
->get();

How to get first entry from the record in Laravel relation?

I got this query, it fetch results from my database, based on relationships.
The query works fine, but it grabs the first entry from the database/table and not the first value of the array.
How can I fix that?
$motor = Motor::query()
->where([
['effect_id', '=', $request->effect_id],
['poles', '=', $request->poles],
['voltage_id', '=', $request->voltage_id],
['active', '=', 1],
])
->whereHas('MotorSize', function (Builder $query) {
$query->whereIn('mounting', ['B5', 'B14', 'B34', 'B35']);
})
->firstOrFail();
I have tried different things, such as:
Adding the orderBy to the Motor model and created a "priority" field in my database, giving each a number between 1 and 100:
(i actually thought this would work, but it still grabs the first entry from the table)
public function MotorSize()
{
return $this->belongsTo('App\MotorSize')->orderBy('priority', 'ASC');
}
I also tried something like this, but it's a mess and never got it to work:
$query->where(function ($query) {
$query->where('mounting', 'like', 'B5');
})
->orWhere(function($query) {
$query->where('mounting', 'like', 'B14');
})
->orWhere(function($query) {
$query->where('mounting', 'like', 'B34');
})
->orWhere(function($query) {
$query->where('mounting', 'like', 'B35');
});
Any suggestions will be welcome :)

Multiple like in a laravel mongo db package not working

I have a project which is creating in laravel and mongodb. I am using a package for connecting to mongodb "https://github.com/jenssegers/laravel-mongodb". I have a table listing. In this table listing there is a text box for search data. For that I used like feature. I have followed the same in documentation but not working. When I search invoice_number data is getting empty. But when I search beds data is getting perfectly. Please correct me.
$bookings = Booking::select('invoice_number', 'temp_user_id', 'user', 'checkin_from', 'reserve_to', 'beds', 'dormitory', 'sleeps', 'status', 'payment_status', 'payment_type', 'total_prepayment_amount', 'txid')
->where('is_delete', 0)
->where('invoice_number', 'like', "%{$search}%")
->orWhere('beds', 'like', "%{$search}%")
->skip($start)
->take($limit)
->orderBy($order, $dir)
->get();
The WHERE statements in your query translate to this:
WHERE [cond_1] AND [cond_2] OR [cond_3]
I doubt this is the condition you need. I'd say you want this:
WHERE [cond_1] AND ([cond_2] OR [cond_3]) -- notice the brackets.
To achieve this, you need a closure in your Builder query. Try this:
$bookings = Booking::select('invoice_number', 'temp_user_id', 'user', 'checkin_from', 'reserve_to', 'beds', 'dormitory', 'sleeps', 'status', 'payment_status', 'payment_type', 'total_prepayment_amount', 'txid')
->where('is_delete', 0)
->where(function($query) use ($search) { /* That's the closure */
$query->where('invoice_number', 'like', "%{$search}%")
->orWhere('beds', 'like', "%{$search}%");
})
->skip($start)
->take($limit)
->orderBy($order, $dir)
->get();
And an example from the docs.

search function look for parameter's value in related table

I have 2 tables, merchants and transaction. merchants has (mid,name,age) and transaction has (id,mid,order_no,). I have displayed the data like (orderid,name) with eagerloading. now i have a search function on top where , i can search for all the orders by the merchant's name. how do i do that? im' trying something like this
public function search($search){
$query = Transaction::with('themerchant')
->join('merchants','transactions.mid', '=', 'merchants.mid' )
->select('merchants.name', '=' , '%'.$search.'%')->paginate(10);
return $query;
}
Oh you are using eagerLoading
Do this
public function search($search){
return Transaction::with(['themerchant' => function($query){
$query->where('name', 'like', '%'.$search.'%');
}])->paginate(10);;
}
If you want an exact merchant match change the where like this
...
->where('name', '=' , $search)
...
If you want to use Join
public function search($search){
return Transaction::join('merchants', 'merchants.mid', '=', 'transactions.mid')
->where('merchants.name', 'like', '%'.$search.'%')
->get();
}

Categories