Skip to content

Instantly share code, notes, and snippets.

@Laratipsofficial
Last active February 10, 2024 02:07
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Laratipsofficial/c9d588c65e55724b41c2b92ca8f33ee6 to your computer and use it in GitHub Desktop.
Save Laratipsofficial/c9d588c65e55724b41c2b92ca8f33ee6 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

@nwaweru
Copy link

nwaweru commented Nov 28, 2022

Nice!

Include use Illuminate\Database\Query\Expression; in the macro too.

@Laratipsofficial
Copy link
Author

Thanks @nwaweru :)
I have included it.

@nwaweru
Copy link

nwaweru commented Nov 28, 2022

Thanks @nwaweru :) I have included it.

Awesome! Keep up the good work man.

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