0

I want to iterate through list of words broken down in a function processNeedle. This is working fine with ordinary php but not in laravel.

    $query = $request->input('query');  

    $trim = new SearchTrim();

    $words = $trim->ProcessNeedle($query);


    $concat = "CONCAT(";        

     $concat.="title,";

    $concat.="'')";


    $sql =DB::select("SELECT DISTINCT id,title,code,abstract FROM projects WHERE 0 ";

    foreach ($words as $word) $sql.=" OR $concat LIKE '%$word%'";
    $sql.=" ORDER BY id DESC";

My query function well like this in php

SQL query: SELECT DISTINCT id,title,code FROM projects WHERE 0 OR CONCAT(title,'') LIKE '%intranet%' OR CONCAT(title,'') LIKE '%mailing%' ORDER BY id DESC;

How do i achieve this in Laravel Please help

9
  • Don't query like that, it will cause sql-injection Commented Apr 28, 2020 at 11:29
  • 1
    Okkk.. But how do I achieve this in laravel? iterating the words from array along with the concat statement Commented Apr 28, 2020 at 11:31
  • why do u concat title with empty string '' and why where 0? Commented Apr 28, 2020 at 11:35
  • SELECT DISTINCT id,title,code FROM projects WHERE 0 OR CONCAT(title,'') LIKE '%intranet%' OR CONCAT(title,'') LIKE '%mailing%' ORDER BY id DESC; Commented Apr 28, 2020 at 11:44
  • This query works perfectly in ordinary php... Its only in laravel its not working.. Commented Apr 28, 2020 at 11:44

1 Answer 1

1

Try this example . i hope it helps you .

Pass foreach inside laravel DB::select query

$items = ['condition1', 'condition2', 'condition3'];
        $results = App\Model::where(function ($query) use ($items) {
            foreach($items as $item) {
                $query->orWhere('dbfield', 'LIKE', "%$item%");
            }
        })
            ->get();
        dd($results);

Sign up to request clarification or add additional context in comments.

1 Comment

Hello, Please how do I edit this query to display the row that have the highest words first

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.