Eloquent query to LIKE query - php

:) In my 40-lines query (Eloquent, Laravel), I have this part:
->orWhere(function ($query) {
$query
->where('questions.category', '=', Auth::user()->category);
})
This works OK, but I want to make it like: '%questions.category%' LIKE Auth::user()->category. I've read I should use CONCAT, but after several tries, I only got a lot of errors. What's the best way to do this? :)

could be you can use this sintax
->where('questions.category', 'like', '%' . Auth::user()->category . '%');

Related

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();

Laravel Query Builder Select with empty Input

I'm building up a filterable list with Laravel 5.0 and I'm crashing on following Problem.
I get the filter parameters from a HTML form and pass them to the Query Builder, but if a form input stays empty all rows of the table filtered by the other filters should be returned.
Example code:
$collection = Model::withTrashed()
->where('attr1', 'LIKE', \Request::input('attr1', '%'))
->where('attr2', 'LIKE', \Request::input('attr2', '%'))
->where('attr3', 'LIKE', \Request::input('attr3', '%'))
->get();
This seems to be most correct code for me, but it doesn't work as expected. Do you know a good solution for my Problem? I don't want to integrate a messy switch/case statement for proofing for existence and building the collection up manually. :(
Thanks for your help.
It seems that your problem is that you are always passing the filters to the query and you should only pass them if they are not empty.
Maybe somethig like this would work for you:
$results = Model::withTrashed();
if (\Request::input('attr1')) {
$results->where('attr1', 'LIKE', \Request::input('attr1', '%'));
}
if (\Request::input('attr2')) {
$results->where('attr2', 'LIKE', \Request::input('attr2', '%'))
}
if (\Request::input('attr3')) {
$results->where('attr3', 'LIKE', \Request::input('attr3', '%'))
}
$collection = $results->get();
You need to tweak your query a bit like this:
$collection = Model::withTrashed()
->where('attr1', 'LIKE', '%' . \Request::input('attr1') . '%')
->where('attr2', 'LIKE', '%' . \Request::input('attr2') . '%')
->where('attr3', 'LIKE', '%' . \Request::input('attr3') . '%')
->get();
This will make sure that the LIKE clause is still correct when an empty input parameter is sent.

Laravel-5 'LIKE' equivalent (Eloquent)

I'm using the below code to pull some results from the database with Laravel 5.
BookingDates::where('email', Input::get('email'))->orWhere('name', 'like', Input::get('name'))->get()
However, the orWhereLike doesn't seem to be matching any results. What does that code produce in terms of MySQL statements?
I'm trying to achieve something like the following:
select * from booking_dates where email='my#email.com' or name like '%John%'
If you want to see what is run in the database use dd(DB::getQueryLog()) to see what queries were run.
Try this
BookingDates::where('email', Input::get('email'))
->orWhere('name', 'like', '%' . Input::get('name') . '%')->get();
I have scopes for this, hope it help somebody.
https://laravel.com/docs/master/eloquent#local-scopes
public function scopeWhereLike($query, $column, $value)
{
return $query->where($column, 'like', '%'.$value.'%');
}
public function scopeOrWhereLike($query, $column, $value)
{
return $query->orWhere($column, 'like', '%'.$value.'%');
}
Usage:
$result = BookingDates::whereLike('email', $email)->orWhereLike('name', $name)->get();
$data = DB::table('borrowers')
->join('loans', 'borrowers.id', '=', 'loans.borrower_id')
->select('borrowers.*', 'loans.*')
->where('loan_officers', 'like', '%' . $officerId . '%')
->where('loans.maturity_date', '<', date("Y-m-d"))
->get();
I think this is better, following the good practices of passing parameters to the query:
BookingDates::whereRaw('email = ? or name like ?', [$request->email,"%{$request->name}%"])->get();
Better:
BookingDates::where('email',$request->email)
->orWhere('name','like',"%{$request->name}%")->get();
You can see it in the documentation, Laravel 5.5.
You can also use the Laravel scout and make it easier with search.
Here is the documentation.
the query which is mentioned below worked for me maybe it will be helpful for someone.
$platform = DB::table('idgbPlatforms')->where('name', 'LIKE',"%{$requestedplatform}%")->first();
If you wish to use it on controller you can do something like:
$generatequery = 'select * from blogs where is_active = 1 and blog_name like '%'.$blogs.'%' order by updated_at desc, id desc';
$blogslists = DB::select($generatequery);
If you are using Postgres, The key word ILIKE can be used instead of LIKE to make the match case-insensitive according to the active locale. This is not in the SQL standard but is a PostgreSQL extension.
this worked for me.
User::where('name, 'ILIKE', $search)->get();
postgres documentation

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();

laravel multiple where clauses within a loop

Pretty much I want the query to select all records of users that are 25 years old AND are either between 150-170cm OR 190-200cm.
I have this query written down below. However the problem is it keeps getting 25 year olds OR people who are 190-200cm instead of 25 year olds that are 150-170 OR 25 year olds that 190-200cm tall. How can I fix this? thanks
$heightarray=array(array(150,170),array(190,200));
$user->where('age',25);
for($i=0;$i<count($heightarray);i++){
if($i==0){
$user->whereBetween('height',$heightarray[$i])
}else{
$user->orWhereBetween('height',$heightarray[$i])
}
}
$user->get();
Edit: I tried advanced wheres (http://laravel.com/docs/queries#advanced-wheres) and it doesn't work for me as I cannot pass the $heightarray parameter into the closure.
from laravel documentation
DB::table('users')
->where('name', '=', 'John')
->orWhere(function($query)
{
$query->where('votes', '>', 100)
->where('title', '<>', 'Admin');
})
->get();
Like Jeemusu and the OP stated, you need to use advance wheres.
But if you want to pass a variable to the closure function you need to make use of the "use" approach:
$heightarray = array(array(150,170),array(190,200));
DB::table('users')
->where('name', '=', 'John')
->orWhere(function($query) use ($heightarray){
//...
})
->get();
I found the answer. I need to include "use" in the closure to pass my $heightarray variable in. Once $heightarray is in then laravel's advance wheres work.
$heightarray=array(array(150,170),array(190,200));
$user->where('age',25);
$userprofile->Where(function($query) use ($heightarray) {
for($i=0;$i<count($heightarray);i++){
if($i==0){
$user->whereBetween('height',$heightarray[$i])
}else{
$user->orWhereBetween('height',$heightarray[$i])
}
}
});
$user->get();
This is completely untested, but looking at the documentation for advance wheres, it would seem you want to try something like this:
DB::table('users')
->where('age',25)
->Where(function($query)
{
for($i=0;$i<count($heightarray);i++){
if($i==0){
$query->whereBetween('height', $heightarray[$i]);
}else{
$query->orWhereBetween('height', $heightarray[$i]);
}
}
})->get();

Categories