Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Tarasovych's avatar

Reusable query parts

Hello!

I want to reuse some query parts in methods below:

public function someQuery()
{
    return DB::table('some_table')
        ->select(...)
        ->join(...) //I want reuse this join
        ->join(...) //I want reuse this join
        ->join(...) //I want reuse this join
        ->where(...)
        ->groupBy(...)
        ->get();
}

public function someOtherQuery()
{
    return DB::table('other_table')
        ->join(...) //I want reuse this join
        ->join(...) //I want reuse this join
        ->join(...) //I want reuse this join
        ->where(...)
        ->count(...);
}

Is it possible somehow? My goal is removing code duplication.

Thanks in advance!

0 likes
2 replies
Braunson's avatar

If you use Models (not DB) you can create global/scopes and relations. As for DB there's no easy helper like that AFAIK. What you could do is create a function that takes care of this once for you. Like so:

protected function dbQuery($table_name)
{
    return DB::table($table_name)
            ->join(...) //I want reuse this join
            ->join(...) //I want reuse this join
            ->join(...); //I want reuse this join
}
public function someQuery()
{
    return $this->dbQuery('some_table')
                ->select(...)
                ->where(...)
                ->groupBy(...)
                ->get();
}

public function someOtherQuery()
{
    return $this->dbQuery('some_table')
                ->where(...)
                ->count(...);
}
1 like
Snapey's avatar

You can pass a part-built query around as it is an object

protected function usualJoins($query)
{
    return $query
            ->join(...) //I want reuse this join
            ->join(...) //I want reuse this join
            ->join(...); //I want reuse this join
}

and then tag it onto any other query

public function someQuery()
{
    $query = DB::table($table_name)
                ->select(...)
                ->where(...)
                ->groupBy(...);

    return $this->usualJoins($query)->get();
}
1 like

Please or to participate in this conversation.