zundi
zundi

Reputation: 2457

Create nested OR condition using Laravel Eloquent

I want to create something like:

select * from documents where 'chapter'=3 and 'section'=4 and ('title' like '%abc% OR 'desc' like %abc%);

How can I do this using Eloquent? I've tried using Eloquent's whereOr method but that doesn't seem to do anything in the generated SQL. But, even if they did, I'm not certain my current code would make them embedded like what I'm looking for.

Some of what I've got:

    $docSearch = DB::table('documents');

    if ($chapter > 0) {
        $docSearch->where('chapter', $chapter);
    }

    $existingManagementArray = Management::getAllManagementIDsAsArray();
    if ($management_id > 0 && in_array($management_id, $existingManagementArray)) {
        $docSearch->where('management_id', $management_id);
    } else {
        $docSearch->whereIn('management_id', $existingManagementArray);
    }

    if (strlen($term) > 0) {
        //HELP! These don't seem to change the SQL
        $docSearch->whereOr('title', 'like', "%$term%"); 
        $docSearch->whereOr('desc', 'like', "%$term%");
    }

    DB::enableQueryLog();
    $allFoundDocs = $docSearch->get();
    dd(DB::getQueryLog());

Upvotes: 3

Views: 3782

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

This should work for you:

DB::table('documents')->where('chapter', 3)
    ->where('section', 4)
    ->where(function($q) use($abc) {
        $q->where('title', 'like', '%'.$abc.'%')
          ->orWhere('desc', 'like', '%'.$abc.'%');
    })->get();

Passing a Closure into the where() method instructs the query builder to begin a constraint group.The Closure will receive a query builder instance which you can use to set the constraints that should be contained within the parenthesis group.

Docs (section called Parameter Grouping)

Upvotes: 4

Related Questions