Mohamed Benhida
Mohamed Benhida

Reputation: 23

laravel 5 search multiple fields

I have a php code in multiple search field but i dont know How i can use this function in laravel

the mysql syntax in laravel it's not the same in simple php so how i can compile it.

if(isset($_GET['submit'])) {
// define the list of fields
      if(isset($_GET['debit']) && !empty($_GET['debit'])) {

    $_GET['valeur'] = - $_GET['debit'];
  }
  else
  {
    if(isset($_GET['credit']) && !empty($_GET['credit']))
    {
        $_GET['valeur'] = $_GET['credit'];
    }
  }
    $fields = array('id_type', 'date_operation', 'date_valeur', 'numero','tiers','description','valeur');
    $conditions = array();


// builds the query
$query = "SELECT * FROM ecritures WHERE id_compte ='" . $iduser . "' ";


// loop through the defined fields
foreach($fields as $field){
    // if the field is set and not empty
    if(isset($_GET[$field]) && !empty($_GET[$field])) {
        // create a new condition while escaping the value inputed by the user (SQL Injection)
        $conditions[] = "$field LIKE '%" . mysqli_real_escape_string($co, $_GET[$field]) . "%'";
        }
    }


// if there are conditions defined
if(count($conditions) > 0) {
    // append the conditions
    $query .= " AND " . implode (' AND ', $conditions); // you can change to 'OR', but I suggest to apply the filters cumulative
}}

Upvotes: 2

Views: 2801

Answers (1)

ptvty
ptvty

Reputation: 5664

The query builder in Laravel makes this kind of queries much easier than creating SQL queries manually like your code.

So this code should work for you:

$q = DB::table('ecritures ')->where('id_compte', $iduser);


// loop through the defined fields
foreach($fields as $field){
    // if the field is set and not empty
    if(isset($_GET[$field]) && !empty($_GET[$field])) {
        // create a new condition
        $q = $q->where($field, 'LIKE', '%' . $_GET[$field] . '%');
    }
}

$result = $q->get();

foreach ($result as $row) {
    echo $row->column_name;
}

I also omitted the escape function as Laravel takes care of that for you.

Upvotes: 2

Related Questions