Skip to content

Instantly share code, notes, and snippets.

@DominikStyp
Forked from Laratipsofficial/lateral join.md
Created July 20, 2024 16:34
Show Gist options
  • Save DominikStyp/a74452752b8d122547ad86f66f0c3521 to your computer and use it in GitHub Desktop.
Save DominikStyp/a74452752b8d122547ad86f66f0c3521 to your computer and use it in GitHub Desktop.
Implementing lateral join in Laravel

Implementing lateral join in Laravel

Making of joinLateral macro

use Illuminate\Database\Query\Builder;
use Illuminate\Database\Query\Expression

Builder::macro('joinLateral', function ($query, $as, $type = 'inner') {
    [$query, $bindings] = $this->createSub($query);

    $expression = 'lateral ('.$query.') as '.$this->grammar->wrapTable($as).' on true';

    $join = $this->newJoinClause($this, $type, new Expression($expression));

    $this->joins[] = $join;

    $this->addBinding($bindings, 'join');

    return $this;
});

Using the macro

use App\Models\Login;
use App\Models\User;

User::query()
    ->select(['users.name', 'latest_logins.logged_in_at'])
    ->joinLateral(
        Login::whereColumn('logins.user_id', 'users.id')
            ->latest('logins.logged_in_at')
            ->limit(3),
        'latest_logins'
    )
    ->get();

Check out video implementing it

Lateral Join Implementation In Laravel

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment