Big A
Big A

Reputation: 31

Laravel Query builder condition with current query using when

How can I create a condition using current query with laravel query builder, is it even possible, i guess it would look something like this

$record = $this->repository
   ->where('value', $value)
   ->when($thisQuery->get()->isNotEmpty(), static function(){
    //execute
    });

Upvotes: 2

Views: 603

Answers (1)

Mahmood Ahmad
Mahmood Ahmad

Reputation: 494

You can use sub-queries in anonymous function as in the example below:

 $record = $this->repository
            ->where('value', $value)
            ->where(function($query) {
                /** @var $query Illuminate\Database\Query\Builder  */
                return $query->where('foo', 'LIKE', '%foooo%')
                             ->orWhere('foo', 'bar');
            })
            ->get();

You can as well run multiple where clauses as in the following:

 $record = $this->repository
            ->where('value', $value)
            ->where('foo', 'bar')
            ->get();

And depends on the requirements use the appropriate way.

Upvotes: 2

Related Questions