What is meant by whereRaw in PHP Laravel framework - php

I'm unsure what whereRaw is in PHP Laravel framework. Could you provide good and easily understandable example, please?

WhereRaw() is a function of Laravel query builder which puts your input as it is in the SQL query's where clause.
Think of it as the where() function whose input argument will not be processed before inserting into queries.
See the example below:
$Query = DB::table('some_table')->where('YEAR(date)', 'YEAR(CURRENT_DATE)');
In this Laravel will resolve your arguments to build a query. Which will result in the following query because your input will be treated as some field and its its value :
SELECT * FROM `some_table` WHERE `YEAR(date)` = `YEAR(CURRENT_DATE)`
Which is not desired.
And now if you use whereRaw like:
$Query = DB::table('some_table')->whereRaw('YEAR(date) = YEAR(CURRENT_DATE)');
Now Laravel put this where clause as it is in your query, like below:
SELECT * FROM `some_table` WHERE YEAR(date) = YEAR(CURRENT_DATE)
Hope it helped (:

WhereRaw: Sometimes you may need to use a raw expression in a query. These expressions will be injected into the query as strings.
If you are unable to generate the query you need via the fluent interface, feel free to use whereRaw()
Ex:
$users = User::whereRaw('age > ? and votes = 100', array(25))->get();
which is equals to:
"SELECT * FROM users WHERE age > 25 AND votes = 100";
Reference

In laraval we use query builder. But Sometime you need to execute raw sql query.
So you can inject it to whereRaw as this example :
whereRAW('YEAR(event_datetime) =?', [$year])

Related

i want to use both query in the following code when is used orWhereNull i am getiing error how i can make my code to run

I want to get the null expiry date result. My whereRaw is working fine but when I used orWhereNull, I get an error. Here is my code:
$offer_details = #\App\Offer::where('store_id',$store_id)->whereRaw('expiry_date > now()')->orWhereNull('expiry_date ')->get();
Following query should work for you as, I don't thing 'orWhereNull()' available in laravel :
$offer_details = #\App\Offer::where('store_id',$store_id)->
->whereNull('expiry_date')
->orWhereRaw('expiry_date > now()')
->get();
Unlike that the "or" variant of 'whereRaw()' is availble as 'orWhereRaw()'.
More details of : whereRaw / orWhereRaw
The whereRaw and orWhereRaw methods can be used to inject a raw where clause into your query. WhereRaw() is a function of Laravel query builder which puts your input as it is in the SQL query's where clause.

Write a query manually into the laravel

I have a little problem, I want to try to take the data with a custom query on laravel but when I try foreach I can't get the data. anyone can help me
This script on the controller :
$data = DB::Statement('SELECT NM_PERUSAHAAN,
count(*) as total_count,
sum(FLAG_TERIMA) as approved,
sum(1 - FLAG_TERIMA) as not_approved
from MSTBEASISWAS
group by NM_PERUSAHAAN;');
foreach ($data as $datas) {
echo $datas;
}
Error :
Here is the difference
DB::raw()
It generates a raw and sanitized SQL string, to be passed to other query/statements, preventing SQL injections. Is to be used with all of the and never alone. And you should never send a not sanitized string to your query/statements.
DB::select(DB::raw('select * from whatever'));
DB::select()
Is for simple selects:
DB::select(DB::raw('select * from whatever'));
DB::statement()
I think it work with selects, but should be used for non SQL query commands:
DB::statement(DB::raw('update whatever set valid = true;'));
DB::unprepared()
All SQL commands in Laravel are prepared by default, but sometimes you need to execute a command in an unprepared mode, because some commands in some database cannot be ran in prepared mode. Here's an issue I opened about this:
https://github.com/laravel/framework/issues/53
DB::unprepared(DB::raw('update whatever set valid = true;'));
Ref: Difference between Laravel's raw SQL functions
The DB::statement() method is used to execute SQL statements without returning result instead return true/false.
You're trying to use this boolean as a query result that why you've this message back from the foreach loop, if you want to run a select statement, you could use DB::select(), e.g :
DB::select('select query here');
Hope this helps.
You can write custom query like:
$data = DB::select(DB::raw('your query here'));
You can do as follows :
$data = DB::select($your_select_query);
The "statement" method of the DB facade returns a boolean value, which tells you whether the query execution was successful or not. Therefore foreach can not process it and throws an exception.
You can understand this by looking at the 2nd line of the exception stack trace.
array('data' => true)
So, to run a raw query string use the following code:
DB::select(DB::raw('SELECT NM_PERUSAHAAN,
count(*) as total_count,
sum(FLAG_TERIMA) as approved,
sum(1 - FLAG_TERIMA) as not_approved
from MSTBEASISWAS
group by NM_PERUSAHAAN;'));
DB::statement will not return data. if you are performing queries which don't return data, then using a SELECT query will result errors. For example, if you want to start the auto-increment ID of a MySQL table to something other than zero, we can use the statement method.
for the above query you have to use DB::select.
$data=DB::Statement('SELECT NM_PERUSAHAAN,
count(*) as total_count,
sum(FLAG_TERIMA) as approved,
sum(1 - FLAG_TERIMA) as not_approved
from MSTBEASISWAS
group by NM_PERUSAHAAN;');

Add custom field during select mysql in laravel query

I have this query in laravel 5.2
$obj_custom_stdy_data = QstCustomStudyData::where('student_id', $this->data_user['student_id'])
->select($list_id . ' as list_id ', 'chapter_id', 'subject_id', 'subject_code_id')
->get()
->toArray();
Well I have a fixed value $list_id got from top code. Actually I want to add new field during query selection as list_id. However I got error for such that method.
When I tried in mysql IDE for example:
SELECT (1+2) as total, c.* FROM users
Then the result is no wrong at all.
Is that anyway to write in query builder for laravel instead of raw style?
You can take the use of DB::raw() method of QueryBuilder like this:
->select(DB::raw('(1+2) as total'));
See more about Query Builder's Raw Expressions
Hope this helps!

Phalcon PhP - how to execute query inside a controller with parameters

I would like to know how can I execute a query, inside a phalcon controller, using parameters.
My SQL Query:
SELECT a.*, getApplicationData(a.id) as json_data
FROM application a
INNER JOIN application_data d on d.application_id = a.id
WHERE a.form_id=1
AND d.firstname LIKE '%:searchQuery:%' ;
Here is how I'm trying to execute (I found it in Phalcon's doc, but the example was not inside a controller).
$applications = $this->db->query(
$sqlQuery,
array('searchQuery'=>$searchQuery)
)->fetchAll();
I know that since you have the ORM I shouldn't be querying the DB like this, but for the feature I'm working on it has to be like this, this query is dymanic.
My question is how to pass the parameter for the :searchQuery: in the query.
Thanks in advance for any help.
You almost got it right. You only had to add the percents (%) in the bind array.
$sqlQuery = 'SELECT * FROM events WHERE title LIKE :searchQuery';
$applications = $this->db->query(
$sqlQuery,
array('searchQuery'=> '%' . $searchQuery . '%')
)->fetchAll();
Also notice how I binded the :searchQuery in the $sqlQuery. It only uses single : instead of surrounding the parameter. This is because Raw queries use directly the DB connection in our case it is PDO.
More examples can be found here: https://docs.phalconphp.com/en/latest/api/Phalcon_Db_Adapter_Pdo.html

Using DB::select() in Laravel with LIKE clause and a variable column name

In the docs,
$results = DB::select('select * from users where id = ?', array(1));
The Problem
I have a variable $column and $value and I want them to search the database based on what column like this:
$results = DB::select('select * from users where ? LIKE "%?%"', array($column, $value));
But this throws an error:
SQLSTATE[42P18]: Indeterminate datatype: 7 ERROR: could not determine data type of parameter $2 (SQL: SELECT * FROM test WHERE refno LIKE '%te%')
I tried hard-coding the value like this:
$results = DB::select('select * from users where ? LIKE "%te%"', array($column));
but it returns a blank array.
How do I do this? Please help.
EDIT:
The query is actually long (with multiple joins). So I prefer not to use the Query Builder style if possible. But if it's not possible, then I will just use Query Builder.
Info:
Laravel v4.2
PostgreSQL
It could be done in more Query Builder style, like that:
$results = DB::table('users')
->where($column, 'LIKE', '%' . $value . '%')
->get();
EDIT
The only reliable way how to do it with DB::select() is:
$results = DB::select("select * from users where ? LIKE '%?%'", array($column, $value));
It produces the right query, I checked it against the database, but also a blank array, or wrong results. Even if this method somehow worked, you still have to escape table and columns names manually, which is tedious and apparently does not work with ?. If you lets say had a $column named values this method would break, since values is a reserved word (at least in MySQL).
The Query Builder method is highly advised, because it also automatically adds SQL escapes to table and column names. Also it is is more portable across DB drivers. It also supports joins with ease. No need to use the method you wants.
the only way i find working
$phone = '%'.$phone.'%';
$seachbyphone = DB::select('SELECT * FROM user WHERE phoneno LIKE ?',[$phone]);
try this:
use App\User; //don't forget add this to header
$result = User::where('columnName', 'LIKE', "%$value%")->get();
LIKE '%?%'" is incorrect. It must be ? only as sql query only expects ? =>vacancy/placeholder for value. Not any single comma or wildcard.
So You need to add % sign with value not with ? =>(placeholder), and its safe as well.
That's why we need
$results = DB::select("select * from users where ? LIKE ?, [$column, '%'.$value.'%'.]);
I would not recommend DB::select() to anyone, even though you have perfectly valid SQL that works directly in the database engine Laravel produces peculiar errors with made-up error descriptions. Instead use DB::table('my_table')->select('...') instead.

Categories