Escape Laravel DB:raw query using Eloquent Where - laravel

How do I escape the following query in Laravel, using Eloquent:
$someCollection->where(DB::raw("CONCAT(`field1`, ' ', `field2`)"), 'LIKE', "%".$user_input."%");
I'm wondering if Eloquent's where method is escaping the $user_input parameter, even when using DB::raw like this.
Any ideas?

The short answer is that yes, the 3rd parameter passed to where() called on a Model or an Eloquent Collection will be bound in the query, which will escape it to guard against injection attacks.
Under the hood, the Query Builder doesn't treat your 3rd parameter any differently depending on what you pass for your 1st parameter. So if you pass a raw Expression as the first query, or a column name, it's all good to Laravel, it will just use that value when constructing the WHERE clause. If you omit an operator as your second parameter, that's fine, too, as passing two parameters instead of 3 is like passing an = for your operator.
When Laravel submits your query to your database, it will actually look like this:
select * from `table_name` where CONCAT(`field1`, ' ', `field2`) LIKE ?
Laravel (technically PDO) then binds the value you submitted in place of the ? placeholder. As a result, any value you pass will be bound and escaped automatically for you.
Now, with escaping, no need to worry about the % operators, as PDO will leave them alone, and your LIKE clause would match any row where the concatenation of field1, a space, and field2, contains the string provided by the user anywhere in it.
You can test this out by passing just a " character as your input. If it wasn't escaped, the query would throw an error, but since it is escaped, the script runs fine - though it may return no results.
Hope that helps!

Related

Is it possible to pass LIVE VIEW name as a parameter in Clickhouse query?

For example, like
CREATE LIVE VIEW %(live_view_name)s WITH REFRESH
It works only with other parameters (WHERE condition) but not with view name.
Look like you use python for make HTTP query?
I think it's not possible because parameter value will escape as string literal, not as field name
Look to
https://clickhouse.com/docs/en/interfaces/http#cli-queries-with-parameters
and
https://clickhouse.com/docs/en/interfaces/cli#cli-queries-with-parameters
and try to use CREATE LIVE VIEW {live_view_name:Identifier} WITH REFRESH

Laravel TNTSearch keyword matchings

Using Laravel TNTSearch how can I define different cases for keywords to end up with the same result on query.
Having the following keyword Softwareentwickler I want to be able to get the same result on Software-Entwickler keyword as well.
Is there any workaround for this case?
The technique you want is called query expansion. What you have to do is simply replace the query with the one you want and perform the search.
Take a look at this
Here, when someone searches for Russia it will replace the query with russian federation

Use a Field value in a Query (Seblod Query plugin)

I'm using the Query plugin that lets me create a Query field on my List & Search.
I have a hidden field with ID 'id_number' which I'm trying to use in my query. When I check the Page Source(Ctrl+U on Chrome), the hidden field has the correct value of id_number which is '22865'.
The part of my Query is-
WHERE [MATCH]p.pid||$cck->getValue('id_number')[/MATCH] AND (ban_reason in ("", "active"))
When I print this query out using the Debugger, the Query is using the literal value and querying the above as-
(p.pid LIKE '%$cck->getValue(\'id\_number\')%') ....and not like (p.pid LIKE '%22865%')
I also tried using $fields['id_number']->value but it still queries it incorrectly.
Should I not use $cck->getValue('id_number') to get the value of the hidden field in the query? Or is there something other than this that I need to use?

Laravel Query Builder, selectRaw or select and raw

What's the difference between:
DB::table('some_table')
->selectRaw('COUNT(*) AS result')
->get();
and:
DB::select(DB::raw("
SELECT COUNT(*) AS result
FROM some_table"));
In the documentation https://laravel.com/docs/5.6/queries they advert about using raw()due SQL Injection, but it's the same with selectRaw?
The end result of both is the same i.e but there are some difference:
The first one:
DB::table('some_table')
->selectRaw('COUNT(*) AS result')
->get();
Returns a collection of PHP objects,
You can call collections method fluently on the result
It is cleaner.
While the second:
DB::select(DB::raw("
SELECT COUNT(*) AS result
FROM some_table"
));
Returns an array of Php object.
Although they have similarities: the raw query string.
Those two examples yield the same result, although with different result data types.
Using raw queries can indeed be an attack vector if you don't escape values used within the query (especially those coming from user input).
However that can be mitigated very easily by using bindings passed as the second parameter of any raw query method, as showcased in the same documentation (selectRaw accepts a second parameter as an array of bindings, as well as other raw methods from the Query Builder such as whereRaw, etc). Actually at the begining of the docs page you referenced, the second paragraph also states the following:
The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.
So as long as you're careful and make sure any parameters are passed as bindings and not concatenated as plain values within the raw query string you should be safe.

How to construct subquery in the form of SELECT * FROM (<subquery>) ORDER BY column;?

I am using gorm to interact with a postgres database. I'm trying to ORDER BY a query that uses DISTINCT ON and this question documents how it's not that easy to do that. So I need to end up with a query in the form of
SELECT * FROM (<subquery>) ORDER BY column;
At first glance it looks like I need to use db.QueryExpr() to turn the query I have into an expression and build another query around it. However it doesn't seem gorm has an easy way to directly specify the FROM clause. I tried using db.Model(expr) or db.Table(fmt.Sprint(expr)) but Model seems to be completely ignored and fmt.Sprint(expr) doesn't return exactly what I thought. Expressions contain a few private variables. If I could turn the original query into a completely parsed string then I could use db.Table(query) but I'm not sure if I can generate the query as a string without running it.
If I have a fully built gorm query, how can I wrap it in another query to do the ORDER BY I'm trying to do?
If you want to write raw SQL (including one that has a SQL subquery) that will be executed and the results added to an object using gorm, you can use the .Raw() and .Scan() methods:
query := `
SELECT sub.*
FROM (<subquery>) sub
ORDER BY sub.column;`
db.Raw(query).Scan(&result)
You pass a pointer reference to an object to .Scan() that is structured like the resulting rows, very similarly to how you would use .First(). .Raw() can also have data added to the query using ? in the query and adding the values as comma separated inputs to the function:
query := `
SELECT sub.*
FROM (<subquery>) sub
WHERE
sub.column1 = ?
AND sub.column2 = ?
ORDER BY sub.column;`
db.Raw(query, val1, val2).Scan(&result)
For more information on how to use the SQL builder, .Raw(), and .Scan() take a look at the examples in the documentation: http://gorm.io/advanced.html#sql-builder

Resources