Search code examples
laraveleloquentlaravel-8query-builderlaravel-query-builder

Laravel Query Builder with Join and If condition


how can you use the if else condition in the results of the query builder?

$data = DB::table('peminjaman')
                        ->select('peminjaman.id as id_peminjaman',
                                'reads.pageread',
                                'books.*',
                                'pengarang.name as pengarang_name'
                                )
                        ->join('reads','reads.id_book','peminjaman.id_book')
                        ->join('books','books.id','=','reads.id_book')
                        ->join('pengarang','pengarang.id','=','books.idpengarang')
                        ->where('peminjaman.id_user',$user->id)
                        ->orderBy($sort,$urut)
                        ->get();
   

i want to use some if conditioning like this, in real case there will be lots of other where, and the table used for where I have declared a join as above

  if($statment=="notread"){
            where('reads.pageread', '=',0);
        }
        if($statment=="read"){
            where('reads.pageread', '=',1);
        }
        if($statment=="bigbook"){
            where('books.bigbook', '=',1);
        }      

  

Solution

  • Just copy paste your query and some touch up, here's the result. Just improve your query builder in case you want to make it more complex

    $data = DB::table('peminjaman')
    ->select(
             'peminjaman.id as id_peminjaman',
             'reads.pageread',
             'books.*',
             'pengarang.name as pengarang_name'
            )
    ->join('reads', 'reads.id_book', '=', 'peminjaman.id_book')
    ->join('books', 'books.id', '=', 'reads.id_book')
    ->join('pengarang', 'pengarang.id', '=', 'books.idpengarang')
    ->where('peminjaman.id_user', $user->id)
    ->when($statement, function($query, $statement){
          if($statement === 'notread'){
                return $query->where('reads.pageread', 0);
          } elseif($statement === 'read'){
                return $query->where('reads.pageread', 1);
          } elseif($statment=="bigbook"){
                return $query->where('books.bigbook', 1);
          }
    })
    ->orderBy($sort, $urut)
    ->get();