Query builder in laravel 8

Laravel query builder use PDO parameter bindings but PDO does not support binding column name.

Retrieve all results form a table:

return $users;

Retrieve all result of specific column name

return $users;

Using where clause to get all result:

return $users;

Retrieve a Single Row from a table:

return $users; 

Retrieve a single row with where clause:

return $users;

Retrieve a single row by its id:

return $users;

Chunking Result:

If we have thousand of result, we may want to get 100 records each time


foreach($users as $user){

We may strop further chunks from going forward using returning false


foreach($users as $user){

return false;

If update and chunk are occurring at the same time it may cause some unexpected behavior.If we plan to update the record while chunk, we should use chunkbyid

Lazy Method:

Lazy Method returns the result as chunk but we can interact the result one by one.

DB::table(‘users’)->orderby(‘id’)->lazy()->each(function ($user){


If we plan to update the record using Lazy Method, we should use LazyByID





Query Builder also support count, max, min, avg and sum.



Find the record if exist or doesntExist. It will return true or false

$user= DB::table('users')->where('name','Hri')->exists();$user= DB::table('users')->where('name','Hri')-> doesntExist();

Select statement:


Getting Distinct Value:


Adding additional column:


return $querytwo;

We can sent the string using DB::raw.

  $string='count(*) as id, name';
  $users = DB::table('users')
->where('name', '=', "Hri")

Note: Raw statements will be added as strings, so we should avoid creating SQL injection vulnerabilities.

Also check out the other blog ..

Http request In Laravel and the form data


For more info:https://laravel.com/docs/8.x/queries

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top