0

I have the following Laravel Eloquent code, where there will be a lot of method chaining:

$foo = EloquentFoo::orderBy('xyz');

if(true)
{
    $foo->whereHas('eloquentModel',function($q){
        return $q->where('name','=','john');
    });
}

Given complex conditions, i need to instantiate the Eloquent Query Builder without using 'orderBy' or any other static methods.

I tried using the following, which fails miserably(don't know why):

$foo = new EloquentFoo;
Mysteryos
  • 5,581
  • 2
  • 32
  • 52

2 Answers2

3
// get the query
$fooQuery = EloquentFoo::query();

// chain methods    
if (whatever) $fooQuery->whateverMethod();

// execute
$fooQuery->get();
Jarek Tkaczyk
  • 78,987
  • 25
  • 159
  • 157
0

A simple way around: I compare my primary key to something non-existing (not an OPTIMAL solution), would be interested to see the other solutions, though I thought this could help:

$foo = EloquentFoo::where('id','!=','0'); // id is the primary key and there is no row with value 0
// so basically above I am searching everything
// Perform Chaining Operation 
if(true)
{
    $foo->whereHas('eloquentModel',function($q){
        return $q->where('name','=','john');
    });
}

Note: You can use id as many times in the chain as you want and it would still work:

EloquentFoo::where('id','!=','0')->where('id','!=','0')->get() 

Hopefully it helps ( I know it is not at all OPTIMAL).

Chintan Parekh
  • 1,101
  • 1
  • 12
  • 31