Alien
Alien

Reputation: 724

Laravel dynamic where queries using Query Builder

I am in new in Laravel. I want to make dynamic where queries with laravel query builder.
Normally I can make dynamic queries in php

$where = array(
  'hello' => 'world'
);

function get($where = null){
   if($where == "")  $where = "";
  //Function which converts where clause into queries
  wheretoqueries($where);  //converts where clause
  $sql = "SELECT * FROM $tbl $where";
  return $sql; 
}
echo get($where);

If where clause is null queries will be

SELECT * FROM $tbl

If where clause is not null queries will be

SELECT * FROM $tbl WHERE hello = "world"

Laravel orm works fine for where clause if key and value exists

A::where($where)->get();

If where is null following method will not work

Upvotes: 6

Views: 11945

Answers (2)

Md. Abutaleb
Md. Abutaleb

Reputation: 1645

Try this. If $where variable contain something then the query will execute otherwise it will retrieve all data from A Model.

 function get($where = null){
     if($where != null){
        A::where('field_name', '=', $where)->first(); 
     }else{
        A::all();
     }
  }

Note: if your query return more than one value then you have to use get() method at end of query builder instead of first(); Reference: https://laravel.com/docs/5.3/queries#where-clauses

Upvotes: 0

Amit Gupta
Amit Gupta

Reputation: 17708

You can chain the where queries as:

$query = Model::query();

if (!empty($value)) {
   $query->where('column', $value);
}

$query->get();

OR

You can use when method as:

Model::when($value, function ($query) use ($value) {
        return $query->where('column', $value);
    })
    ->get();

Upvotes: 9

Related Questions