Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I build a condition based query in Laravel?

Tags:

php

laravel

I can do this in Code Igniter:

$this->db->select(); $this->from->('node'); if ($published == true) {     $this->db->where('published', 'true'); } if (isset($year)) {     $this->db->where('year >', $year); } $this->db->get(); 

How can this code be translated so that it works in Laravel?

like image 870
Amitav Roy Avatar asked Jan 06 '13 05:01

Amitav Roy


People also ask

Which is better eloquent or query builder in Laravel?

When you are handling more data, it is better to use Laravel's DB facade query builder than Laravel's Eloquent ORM. From performance tests, inserting 1000 rows in a simple table takes Eloquent 1.2 seconds whereas the DB facade takes only 800 milliseconds.

What is query Builder in Laravel with example?

Introduction. Laravel's database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application and works perfectly with all of Laravel's supported database systems.

What is ADD or condition in Laravel?

Laravel multiple where conditions - [OR]: What if you want to use OR condition in your query? You will have to use orWhere() condition for addition query. Note: First query cannot start with orWhere(). It has to be regular where().

What is fluent query builder in Laravel?

The Fluent Query Builder is Laravel's powerful fluent interface for building SQL queries and working with your database. All queries use prepared statements and are protected against SQL injection. You can begin a fluent query using the table method on the DB class.


1 Answers

In Fluent you can do:

$query = DB::table('node');  if ($published == true)     $query->where('published', '=', 1);  if (isset($year))     $query->where('year', '>', $year);  $result = $query->get(); 
like image 177
BenG Avatar answered Oct 11 '22 20:10

BenG