Laravel 5.0 whereRaw concat like - laravel-5

I am using Laravel 5.0.
I have this:
return User::whereRaw("CONCAT(first_name, ' ', last_name) LIKE '%?%'", ['test'])->get();
and it returns [].
When I change it to:
return User::whereRaw("CONCAT(first_name, ' ', last_name) LIKE '%test%'")->get();
it returns an array with 3 users.
I added this before the query:
\DB::listen(function($sql, $bindings) {
var_dump($sql);
var_dump($bindings);
});
And I get:
string(73) "select * from `users` where CONCAT(first_name, ' ', last_name) LIKE '%?%'"
array(1) {
[0]=>
string(4) "test"
}
I can't figure out what I am doing wrong.

You shouldn't use quotes around the ? placeholder and it shouldn't be part of a longer string. The prepared statement surrounds the value with quotes and/or backticks.
This works:
return User::whereRaw("CONCAT(first_name, ' ', last_name) LIKE ?", ['%test%'])->get();
Notice that the ? is a standalone value. The quotes will be added when the query is executed.

Related

Concate and produce null

I try to make an exception for my function where is address is null, it did not have to print out the null value.
Here is my function:
if (UserAddress::where('address_2', '=', 'null')) {
$a = UserAddress::select("*", DB::raw("CONCAT(user_addresses.address_1,' ',user_addresses.address_2,' ',user_addresses.city,' ' ,user_addresses.postcode,' ',user_addresses.state) as full_address"))->pluck('full_address');
}else{
$a = UserAddress::select("*", DB::raw("CONCAT(user_addresses.address_1,' ',user_addresses.address_2,' ',user_addresses.city,' ' ,user_addresses.postcode,' ',user_addresses.state) as full_address"))->pluck('full_address');
}
When I die dump $a, the first produce null query.
You cannot use arithmetic comparison operators such as =, <, or <> to test for NULL.
Instead of where('address_2', '=', 'null'), try using the whereNull() function like so:
if (UserAddress::whereNull('address_2')) {
$a = UserAddress::select("*", DB::raw("CONCAT(user_addresses.address_1,' ',user_addresses.address_2,' ',user_addresses.city,' ' ,user_addresses.postcode,' ',user_addresses.state) as full_address"))->pluck('full_address');
}else{
$a = UserAddress::select("*", DB::raw("CONCAT(user_addresses.address_1,' ',user_addresses.address_2,' ',user_addresses.city,' ' ,user_addresses.postcode,' ',user_addresses.state) as full_address"))->pluck('full_address');
}
It can help to enable the query log to see what exactly you are querying on the database, then you can run it directly via phpmyadmin (or whatever you are using). Place DB::enableQueryLog(); before you query, and //dd(DB::getQueryLog()) after the query is executed for troubleshooting.
I solve it. Use empty string with CONCAT_WS
DB::raw("CONCAT_WS('',user_addresses.address_1,...

Convert raw SQL query to Eloquent

I need your help, guys. I have this query:
SELECT * FROM users
where lcase(concat(firstname, ' ', lastname)) like lcase(concat('%', replace('%searchterm%', ' ', '%'), '%'))
OR lcase(concat(lastname, ' ', firstname)) like lcase(concat('%', replace('%searchterm%', ' ', '%'), '%'))
OR lcase(location) like lcase('%searchterm%')
Is it possible to use a nice eloquent query instead of DB::select(DB::raw()) to use pagination?
You could use whereRaw and orWhereRaw methods on a Eloquent Builder to use raw expressions while maintaining the ability to get model instances as a result.
The advantages is that you can still use PDO parameter binding and therefore avoid SQL Injections though $searchTerm.
You can also find out more about raw expressions in the documentation;
// Assuming $searchTerm contains the term that you need to search the database for
$users = User::whereRaw('lcase(concat(firstname, " ", lastname)) like lcase(concat("%", replace("%?%", " ", "%"), "%"))', [ $searchTerm ])
->orWhereRaw('lcase(concat(lastname, " ", firstname)) like lcase(concat("%", replace("%?%", " ", "%"), "%"))', [ $searchTerm ])
->orWhereRaw('lcase(location) like lcase("%?%")', [ $searchTerm ])
->get();
To split your where condition you can use orWhere method.
User::
->where(DB::raw('condition_one'))
->orWhere(DB::raw('condition_two'))
->orWhere(DB::raw('condition_three'))
->paginate();

Laravel Eloquent Where Query with multiple words

I have the following query (cut for brevity):
$employees = Employee::where('first_name', 'LIKE', "%$query%")
->orWhere('last_name', 'LIKE', "%$query%")
Now this works when the user inputs a single name like 'John' or 'Smith', but when they input 'John Smith' it doesn't find anything. Am I missing an extra orWhere?
Try this :
Employee::where(DB::raw('CONCAT(first_name," ",lastname)'), 'LIKE', "%' . $query . '%"))
You would have to add a 3rd orWhere. For our search function we use something like this:
Employee::whereraw("COALESCE(last_name, '') LIKE '%$query%'")
->Orwhereraw("COALESCE(first_name, '') LIKE '%$query%'")
->Orwhereraw("COALESCE(last_name + ', ' + first_name, '') LIKE '%$query%'")
Adding Coalesce seemed to help with some issues we had when we first implemented it, not sure if it is necessary in your case though.
You can do :
$fullName = trim($query);
$employees = Employee::where(DB::raw("CONCAT(first_name, ' ', last_name)"), 'LIKE', "%".$fullName."%")->get();
You are concatenating the values in database for first_name + ' ' + last_name and then using like to find the matching records.

Concat in Codeigniter Active Record

I am trying a Concat for an autocomplete, Using CI's Active Record.
My Query is :
$this->db->select("CONCAT(user_firstname, '.', user_surname) AS name", FALSE);
$this->db->select('user_id, user_telephone, user_email');
$this->db->from('users');
$this->db->where('name', $term);
I keep getting an MySQL Error from this saying:
Error Number: 1054Unknown column 'name' in 'where clause'
Which is true, However I have just created in my Concat clause. I ideally need $term to match the Concatenated firstname and surname fields.
Any ideas what I can do to improve this? I am considering just writing this as an flat MySQL Query..
Thanks in advance
$this->db->select('user_id, user_telephone, user_email, CONCAT(user_firstname, '.', user_surname) AS name', FALSE);
$this->db->from('users');
$this->db->where('name', $term);
Not sure why you are running multiple selects. So just put it as a single select. It's probably that the 2nd one is overriding the first one and thus overwriting the concatenation to create the name column.
$this->db->select("CONCAT((first_name),(' '),(middle_name),(' '),(last_name)) as candidate_full_name");
Try like above 100% it will work in ci.
If cryptic solution doen't work then try it.
$query = "SELECT *
FROM (
SELECT user_id, user_telephone, user_email, CONCAT(user_firstname, ' ', user_surname) name
FROM users
) a
WHERE name LIKE '%".$term."%'";
$this->db->query($query);
Source: MySQL select with CONCAT condition
You have to SELECT the fields that you want concat like so:
$this->db->select('user_id, user_telephone, user_email, user_firstname, user_surname, CONCAT(user_firstname, '.', user_surname) AS name', FALSE);
$this->db->from('users');
$this->db->where('name', $term);
This will also solve the issue:
$this->db->select('user_id, user_telephone, user_email, user_firstname, user_surname, CONCAT(user_firstname,user_surname) AS name', FALSE);
$this->db->from('users');

CodeIgniter query syntax error

I am facing a syntax issue with a CodeIgniter database query. Can't figure out what's wrong.
$query = $this->db->query("
INSERT IGNORE INTO ".$table." (email, lang, ip_address)
VALUES (".$this->db->escape($_POST['email']).", ".$this->db->escape($lang).", ".$this->input->ip_address().")");
I am also looking for a way to output what the query looks like once the placeholders are replaced, as I am little confused with CodeIgniter debugging options.
It looks as though you are not escaping the strings that you're trying to input into the database. The query you've posted would evaluate to something like:
$query = $this->db->query("
INSERT IGNORE INTO table_name (email, lang, ip_address)
VALUES (email#email.com, en, 192.168.0.1)
");
This will throw an error as the strings in VALUES are not properly escaped. Instead of the query you're running you should use something like:
$query = $this->db->query("
INSERT IGNORE INTO ".$table." (email, lang, ip_address)
VALUES ('".$this->db->escape($_POST['email'])."', '".$this->db->escape($lang)."', '".$this->input->ip_address()."')
");
Note the new ' characters around each string.
use
echo $this->db->last_query();
for retrieving the query runned.
so then check if the query is well formatted.
To know what query you are passing to your database. Use below statement and to insert data into the database. Please follow the below procedure.
echo $this->db->last_query();
$data = array(
'email' => $this->db->escape($_POST['email']),
'lang' = > $this->db->escape($lang),
'ip_address' => $this->input->ip_address(),
);
Call your model function $this->model->insert_function_name($data);
Your model function in your model file
public function insert_function_name($data)
{
$this->db->insert($table_name,$data);
return $this->db->insert_id();
}
Try this : your query was missing single quotes to the string type of value like email, lang and ip
$query = $this->db->query("
INSERT IGNORE INTO ".$table." (email, lang, ip_address)
VALUES ('".$this->db->escape($_POST['email'])."', '".$this->db->escape($lang)."', '".$this->input->ip_address()."')");

Resources