Where clause with a blank variable Laravel - mysql

I use GET, to collect a variable :
$subid = $_GET['subid'];
In my DB Query i have the following :
->where('subID', '=', $subid)
Now if the variable $subid is blank , the result returns no information. How do i specify in the query that if the variable $subid is blank or empty, return all results?

You can use when.
->when($subid, function ($query) use ($subid) {
return $query->where('subID', '=', $subid);
})
If $subid is false the where condition won't be applied to the query.
Check out the doc https://laravel.com/docs/5.2/queries#conditional-statements
UPDATE:
Any expression that you can be used inside an if call can be used as the first argument of when
An example :
->when($fromDate && $toDate, function($query) use ($fromDate, $toDate) {
return $query->whereBetween('CompletedDate', array($fromDate, $toDate));
})

You can use orWhere():
->where('subID', '=', $subid)
->orWhere('subID', '=', '');

Related

Why 'where' return all data in laravel

I am applying search filter in my project so first of all I get data from multiple tables and store in two different variables and then merge these two variable into one so I can filter data from that merged variable. So my code is like that
$data1=Model::query()
->Join('...')
->leftJoin('...')
->where('id',login_user)
->select(...)
->whereRaw('id IN (select MAX(id) FROM table GROUP BY name)')
->groupBy('name')
->get();
$data2=Model2::query()
->leftJoin(...)
->select(...)
->where('id',login_user)
->whereNotIn(..)
->get();
both data1 and data2 return same column with different values so I merge both variable like that
$results = $data1->concat($data2);
No when I already get data so now I need to add filter data from $results so i make post method for that .
so When user request to filter data with name I write query like that
if ($request->name!="") {
$results->when(request('name'), function($q){
$q->Where('name', request('name'));
});
}
$records = $results;
return response()->json(['success'=>true,'message'=>'success', 'data' => $records]);
But that query is not filtering the data and return me all data.I am new in laravel so I don't know what I have done wrong in that any favour will be helpful for me ,thanks.
if (request()->has('name')) {
$results->when(request()->get('name'), function($q){
return $q->where('name', request()->get('name'));
});
}
$records = $results;
return response()->json(['success'=>true,'message'=>'success', 'data' => $records]);
As you use 'when()', you can drop the if expression all together:
$results->when(request()->has('name'), function($q){
return $q->where('name', request()->get('name'));
});
$records = $results;
return response()->json(['success'=>true,'message'=>'success', 'data' => $records]);
request() is a Laravel helper for Request $request
Edit: the where() clause in the ORM is with a small 'w', not 'W' as in orWhere

SQL Laravel Eloquent - Where field can be uppercase or lowercase

$pname can be "Airbus", "airbus" or "AIRBUS"
$info = Plane::where('plane_name', '=', $pname)
->where('uid', '=', $uid)
->get();
Is there any way I can update this query to check the database for the plane name without case sensitivity?
Use LOWER MYsql function and strtolower php function
$info = Plane::whereRaw('LOWER(plane_name) = (?)', [strtolower($pname)])
->where('uid', '=', $uid)
->get();
OR
Plane::where('plane_name', 'ilike', $pname)->where('uid', '=', $uid)
->get();
just make sure result where clause to lowercase and query clause to lowercase too.
where(DB::raw('lower(column_name)'), '=', Str::lower($query))
dont forget to use:
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
Add -> use Illuminate\Support\Facades\DB; in Controller file.
-----------Example---------------
UserInfo::where(DB::raw('upper(username)'), strtoupper($Request->username))
It's work for me, hope to help you.
To solve my issue, I have to do that on my Model.
simple copy and paste this function
public function __get($key)
{
if (is_null($this->getAttribute($key))) {
return $this->getAttribute(strtoupper($key));
} else {
return $this->getAttribute($key);
}
}

Use variable on the mysql like sentence on laravel query builder

$key was a variable can be empty or something.
var key='"<?php echo $_REQUEST['key']; ?>"';
then send to the ajax by data
"ajax": {
"url": "{{asset("try")}}",
"type": 'POST',
"dataType": 'json',
"async": true,
"data": {
key : key,
},
}
the try Controller
public function try(Request $request){
$key=$request->key;
DB::query()
->select('A.id','A.upper_p_id','A.key')
->from('users as A')
->leftjoin('products as B', function($join) {
$join->on('A.ID', '=', 'B.p_id');
})
->groupBy('A.id','A.upper_p_id','A.key')
->where('A.key', 'LIKE', '%'.$key.'%');
->get()
return $result;
}
I got the error expression from the queries debug tool?
LIKE '%\"\"%'
But if I use
->where('A.n_geography','LIKE', '%'.''.'%');
It is right sentence from the queries debug tool.
LIKE '%%'
Well - you did put in the double quotes in the key variable...
So it's doing it correctly :-)
If you are trying to get key from request, you ideally should no use $_GET o $_POST.
public function getData(Request $request){
$key = $request->key;
$records = DB::table('users')
->leftJoin('products', 'users.id', '=', 'products.p_id')
->groupBy('users.id','users.upper_p_id','users.key')
->where('users.key', 'LIKE', '%'.$key.'%')
->select('users.id','users.upper_p_id','users.key')
->get();
return response()->json($records, 200);
}
However if the key variable is a javascript variable, then you can not directly use in controller. You need to pass it somehow in route param or using ajax request.
Secondly if you can add conditional when that if $key is present then only do a where clause :
public function getData(Request $request){
$key = $request->key;
$records = DB::table('users')
->leftJoin('products', 'users.id', '=', 'products.p_id')
->groupBy('users.id','users.upper_p_id','users.key')
->when($key, function($q) use($key){
return $q->where('users.key', 'LIKE', '%'.$key.'%');
})
->select('users.id','users.upper_p_id','users.key')
->get();
return response()->json($records, 200);
}
You're double quoting key. The suggested way to share PHP variables as JS variables is to JSON encode them for example:
var key= {!! json_encode(request()->input('key')) !!};
Note that there are no additional quotes necessary in the JS code because valid JSON is also a valid JS variable.
Also note that since you are using Laravel it is recommended you use blade markup and the request() helper for accessing the request parameters
In order to prevent SQL injection it is better not to concatenate the value directly but pass it as a param so try this:
$key = $request->key;
...
->whereRaw('A.key like ?', ['%' . $key . '%']);
And in your JS:
var key='<?php echo $_REQUEST['key']; ?>';

Laravel Query Builder - where clause equals anything programmatically

I'm using Laravel 5.6 - Query Builder.
Is it possible to make a query builder where statement that a value equals everything programmatically?
Let's say that I have this code:
$foo = 1;
DB::table('users')
->select('*')
->where('status', '=', $foo)
->get();
If $foo = 1 then it's straightforward. The query will select everything with the status of 1.
Q: Is it possible to assign something to the $foo variable so the select query returns every record regardless of the status from the DB?
Of course, I can make it happen with 2 query statements like this:
$foo = 1;
if ($foo === null) {
DB::table('users')
->select('*')
->get();
} else {
DB::table('users')
->select('*')
->where('status', '=', $foo)
->get();
}
However, I'm looking for a shorter / more effective solution. Is it possible somehow - without using raw code inside the Where statement?
You may try something like this:
$query = DB::table('users')->select('*');
// $foo = 'get it...';
if ($foo) {
$query->where('status', $foo);
}
$result = $query->get();
Or even more laravel-ish:
$result = DB::table('users')->select('*')
->when($foo, function ($query) use ($foo) {
return $query->where('status', $foo);
})
->get();
Check more here.

Eloquent: Select field from whereHas block fails

I have got a slightly complex SQL query using a combination of where, whereHas, orWhereHas etc.
Everything goes well but when I add 'custom_records.custom_title' (see below) into the Select fields it fails with:
The Response content must be a string or object implementing __toString(), "boolean" given.
Any ideas?
Here it's the snippet:
`
$record = $this->record->newQuery();`
$record->whereHas('customRecords', function ($query) use ($searchTerm) {
$query->where('custom_title', 'like', '%'.$searchTerm.'%');
});
return $record->get([
'records.id',
'records.another_field',
'records.another_field_2',
'custom_records.custom_title',
]);
Update
When I run the produced SQL query on a mysql client it comes back with:
Unknown column 'custom_records.custom_title',' in 'field list'
You can't select custom_records.custom_title like that. Since it's a HasMany relationship, there can be multiple custom_records per record.
You have to do something like this:
$callback = function ($query) use ($searchTerm) {
$query->where('custom_title', 'like', '%'.$searchTerm.'%');
};
Record::whereHas('customRecords', $callback)
->with(['customRecords' => $callback])
->get(['id', 'another_field', 'another_field_2']);