Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 758
Alien Avatar asked Dec 25 '16 16:12

Alien


People also ask

What is Query Builder in Laravel?

Laravel's query builder provides much convenient and fluent interface to create and run database queries. It uses PDO parameter binding to prevent SQL injection attacks, so, there's no need to clean strings being passed as bindings.

What are the different types of queries in Laravel?

The DB facade provides methods for each type of query: select, update, insert, delete and statement. Laravel's query builder provides much convenient and fluent interface to create and run database queries.

What is Laravel database?

Database: Query Builder - Laravel - The PHP Framework For Web Artisans Laravel is a PHP web application framework with expressive, elegant syntax. We’ve already laid the foundation — freeing you to create without sweating the small things.

What can I do with it in Laravel?

It can be used to perform most database operations in your application and works perfectly with all of Laravel's supported database systems. The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks.


1 Answers

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();
like image 194
Amit Gupta Avatar answered Oct 01 '22 04:10

Amit Gupta