DomeWTF
DomeWTF

Reputation: 2420

Laravel 5 raw select query doesn't return anything

I am trying to retrieve data from a database and i need to run the sql as a raw query, this is how I do it:

$var = Nuti::select(DB::raw("select name, image, info from nuti
  where name like '%:search_term%'"), array("search_term" => $term));

return $var;

$var returns an empty array but when I try to run the same query directly in a mysql console, it returns two records.

[EDIT]

I just shortened the query when i posted this question, the need for a raw query is to do something more like this:

$var = Nuti::select(DB::raw("select name, image, info from nuti
  where name like '%:search_term%'") or info %like% '%:search_term%', array("search_term" => $term));

return $var;

Upvotes: 2

Views: 856

Answers (4)

Sandeesh
Sandeesh

Reputation: 11936

You can do it in the following ways.

$data = Nuti::select(['name', 'image', 'info'])->where('name', 'like', "%{$term}%")->get();

$data = Nuti::selectRaw('name, image, info')->where('name', 'like', "%{$term}%")->get();

$data = DB::table('users')->select(['name', 'image', 'info'])->where('name', 'like', "%{$term}%")->get();

$data = DB::table('users')->selectRaw('name, image, info')->where('name', 'like', "%{$term}%")->get();

$data = DB::select("select name, image, info from nuti where name like '%{$term}%'");

Upvotes: 5

admcfajn
admcfajn

Reputation: 2126

You might just need to add ->get();

$var = Nuti::select(DB::raw("select name, image, info from nuti
      where name like '%:search_term%'"), array("search_term" => $term))->get();

You can debug with:

$var = Nuti::select(DB::raw("select name, image, info from nuti
  where name like '%:search_term%'"), array("search_term" => $term))->toSql(); 
dd($var);

edit: What about this?

$var = Nuti::select(DB::raw("select name, image, info from nuti
      where name like '%:".$term."%'"))->get();

Upvotes: 1

Kyaw Kyaw Soe
Kyaw Kyaw Soe

Reputation: 3370

$var = Nuti::select(['name', 'image', 'info'])->where('name', 'like', "%{$term}%")->get();
return $var;

I think this is all you need.

Upvotes: 0

Paul Spiegel
Paul Spiegel

Reputation: 31832

If your query is too complex for the query builder and you want to get an collection of models from a raw query, you can use hydrateRaw():

$var = Nuti::hydrateRaw(
    "select name, image, info from nuti where name like :search_term",
    array("search_term" => "%{$term}%")
);

Upvotes: 0

Related Questions