Skip to main content

Command Palette

Search for a command to run...

How to fix Integrity constraint violation in Laravel chunkById and lazyById

Updated
1 min read
How to fix Integrity constraint violation in Laravel chunkById and lazyById
G

I am a self-taught developer currently in Salt Lake City. Currently, work in Laravel but have experience in plain PHP, PERL, and CakePHP.

Entrepreneurial VP of tech and CTO with a strong grasp of both the business and engineering. PHP developer for 10 years with experience in CakePHP and Laravel

When using either chunkById or lazyById with Laravel's query builder you must pass an additional parameter to avoid the error SQLSTATE[42702]: Ambiguous column: 7 ERROR: column reference "id" is ambiguous.

lazyById:

User::join('posts', 'posts.user_id', 'users.id)
     ->lazyById(100, 'users.id', 'id')
     ->each(function ($user) {
          // do work
     });

chunkById:

User::join('posts', 'posts.user_id', 'users.id)
     ->chunkById(100, function ($user) {
          // do work
     }, 'users.id', 'id')
M

Thanks, this was super helpful

More from this blog

Laravel & PHP by Guy Warner

18 posts

Self taught programmer -> Freelancer -> Senior Developer -> CTO

Laravel, PHP and all that comes with it.