Debug School

rakesh kumar
rakesh kumar

Posted on • Edited on

Database: Query Builder Laravel

  1. Retrieving All Rows From A Table
  2. Retrieving A Single Row / Column From A Table
  3. Retrieving A List Of Column Values
  4. Chunking Results
  5. Aggregates
  6. Determining If Records Exist
  7. Specifying A Select Clause
  8. Raw Expressions(select)
  9. Raw Methods(selectRaw,whereRaw / orWhereRaw/havingRaw / orHavingRaw,orderByRaw,groupByRaw)
  10. Joins(Inner Join Clause,Left Join / Right Join Clause/Advanced Join Clauses)
  11. Unions
  12. Basic Where Clauses(Where Clauses,where using array)
  13. Or Where Clauses
  14. Where Not Clauses
  15. JSON Where Clauses
  16. whereBetween / orWhereBetween
  17. whereNotBetween / orWhereNotBetween
  18. whereIn / whereNotIn / orWhereIn / orWhereNotIn
  19. whereNull / whereNotNull / orWhereNull / orWhereNotNull
  20. whereDate / whereMonth / whereDay / whereYear / whereTime
  21. whereColumn / orWhereColumn
  22. Logical Grouping
  23. Advanced Where Clauses
  24. Where Exists Clauses
  25. Ordering, Grouping, Limit & Offset
  26. The orderBy Method
  27. The latest & oldest Methods
  28. The groupBy & having Methods
  29. Limit & Offset
  30. The skip & take Methods
  31. Insert Statements
  32. Auto-Incrementing IDs
  33. Update Statements
  34. Update Or Insert
  35. Increment & Decrement
  36. Delete Statements
  37. Debugging
  38. whereId and whereEmail

Some Important Laravel Query Screenshot

get_my_bookings
Image description
Image description
check_booking
Image description

Image description

Retrieving All Rows From A Table
Booking.php
get_my_bookings
Image description

Image description
** Retrieving A Single Row / Column From A Table**
Image description
Image description
Image description

Retrieving A List Of Column Values
Image description
Image description
*Chunking Results *
This method retrieves a small chunk of results at a time and feeds each chunk into a closure for processing. For example, let's retrieve the entire users table in chunks of 100 records at a time:
Image description
Image description
Image description
*Aggregates *

The query builder also provides a variety of methods for retrieving aggregate values like count, max, min, avg, and sum. You may call any of these methods after constructing your query:

use Illuminate\Support\Facades\DB;

$users = DB::table('users')->count();

$price = DB::table('orders')->max('price');
Enter fullscreen mode Exit fullscreen mode

Of course, you may combine these methods with other clauses to fine-tune how your aggregate value is calculated:

$price = DB::table('orders')
                ->where('finalized', 1)
                ->avg('price');
Enter fullscreen mode Exit fullscreen mode

Determining If Records Exist
Instead of using the count method to determine if any records exist that match your query's constraints, you may use the exists and doesntExist methods:

if (DB::table('orders')->where('finalized', 1)->exists()) {
    // ...
}

if (DB::table('orders')->where('finalized', 1)->doesntExist()) {
    // ...
}
Enter fullscreen mode Exit fullscreen mode

Select Statements
Specifying A Select Clause
You may not always want to select all columns from a database table. Using the select method, you can specify a custom "select" clause for the query:

use Illuminate\Support\Facades\DB;

$users = DB::table('users')
            ->select('name', 'email as user_email')
            ->get();
Enter fullscreen mode Exit fullscreen mode

The distinct method allows you to force the query to return distinct results:

$users = DB::table('users')->distinct()->get();

If you already have a query builder instance and you wish to add a column to its existing select clause, you may use the addSelect method:

**$query = DB::table('users')->select('name');

$users = $query->addSelect('age')->get();**

Raw Expressions
Sometimes you may need to insert an arbitrary string into a query. To create a raw string expression, you may use the raw method provided by the DB facade:

$users = DB::table('users')
             ->select(DB::raw('count(*) as user_count, status'))
             ->where('status', '<>', 1)
             ->groupBy('status')
             ->get();
Enter fullscreen mode Exit fullscreen mode

Raw statements will be injected into the query as strings, so you should be extremely careful to avoid creating SQL injection vulnerabilities.

Raw Methods
Instead of using the DB::raw method, you may also use the following methods to insert a raw expression into various parts of your query. Remember, Laravel can not guarantee that any query using raw expressions is protected against SQL injection vulnerabilities.

selectRaw
The selectRaw method can be used in place of addSelect(DB::raw(/* ... */)). This method accepts an optional array of bindings as its second argument:

$orders = DB::table('orders')
                ->selectRaw('price * ? as price_with_tax', [1.0825])
                ->get();
Enter fullscreen mode Exit fullscreen mode

whereRaw / orWhereRaw
The whereRaw and orWhereRaw methods can be used to inject a raw "where" clause into your query. These methods accept an optional array of bindings as their second argument:

$orders = DB::table('orders')
                ->whereRaw('price > IF(state = "TX", ?, 100)', [200])
                ->get();
Enter fullscreen mode Exit fullscreen mode

havingRaw / orHavingRaw
The havingRaw and orHavingRaw methods may be used to provide a raw string as the value of the "having" clause. These methods accept an optional array of bindings as their second argument:

$orders = DB::table('orders')
                ->select('department', DB::raw('SUM(price) as total_sales'))
                ->groupBy('department')
                ->havingRaw('SUM(price) > ?', [2500])
                ->get();
Enter fullscreen mode Exit fullscreen mode

orderByRaw
The orderByRaw method may be used to provide a raw string as the value of the "order by" clause:

$orders = DB::table('orders')
                ->orderByRaw('updated_at - created_at DESC')
                ->get();
Enter fullscreen mode Exit fullscreen mode

groupByRaw
The groupByRaw method may be used to provide a raw string as the value of the group by clause:

$orders = DB::table('orders')
                ->select('city', 'state')
                ->groupByRaw('city, state')
                ->get();
Enter fullscreen mode Exit fullscreen mode

Joins
Inner Join Clause
The query builder may also be used to add join clauses to your queries. To perform a basic "inner join", you may use the join method on a query builder instance. The first argument passed to the join method is the name of the table you need to join to, while the remaining arguments specify the column constraints for the join. You may even join multiple tables in a single query:

use Illuminate\Support\Facades\DB;

$users = DB::table('users')
            ->join('contacts', 'users.id', '=', 'contacts.user_id')
            ->join('orders', 'users.id', '=', 'orders.user_id')
            ->select('users.*', 'contacts.phone', 'orders.price')
            ->get();
Enter fullscreen mode Exit fullscreen mode

Left Join / Right Join Clause
If you would like to perform a "left join" or "right join" instead of an "inner join", use the leftJoin or rightJoin methods. These methods have the same signature as the join method:

$users = DB::table('users')
            ->leftJoin('posts', 'users.id', '=', 'posts.user_id')
            ->get();

$users = DB::table('users')
            ->rightJoin('posts', 'users.id', '=', 'posts.user_id')
            ->get();
Enter fullscreen mode Exit fullscreen mode

Advanced Join Clauses
You may also specify more advanced join clauses. To get started, pass a closure as the second argument to the join method. The closure will receive a Illuminate\Database\Query\JoinClause instance which allows you to specify constraints on the "join" clause:

DB::table('users')
        ->join('contacts', function ($join) {
            $join->on('users.id', '=', 'contacts.user_id')->orOn(/* ... */);
        })
        ->get();
Enter fullscreen mode Exit fullscreen mode

If you would like to use a "where" clause on your joins, you may use the where and orWhere methods provided by the JoinClause instance. Instead of comparing two columns, these methods will compare the column against a value:

DB::table('users')
        ->join('contacts', function ($join) {
            $join->on('users.id', '=', 'contacts.user_id')
                 ->where('contacts.user_id', '>', 5);
        })
        ->get();
Enter fullscreen mode Exit fullscreen mode

Unions
The query builder also provides a convenient method to "union" two or more queries together. For example, you may create an initial query and use the union method to union it with more queries:

use Illuminate\Support\Facades\DB;

$first = DB::table('users')
            ->whereNull('first_name');

$users = DB::table('users')
            ->whereNull('last_name')
            ->union($first)
            ->get();
Enter fullscreen mode Exit fullscreen mode

In addition to the union method, the query builder provides a unionAll method. Queries that are combined using the unionAll method will not have their duplicate results removed. The unionAll method has the same method signature as the union method.

Basic Where Clauses
Where Clauses
You may use the query builder's where method to add "where" clauses to the query. The most basic call to the where method requires three arguments. The first argument is the name of the column. The second argument is an operator, which can be any of the database's supported operators. The third argument is the value to compare against the column's value.

For example, the following query retrieves users where the value of the votes column is equal to 100 and the value of the age column is greater than 35:

$users = DB::table('users')
                ->where('votes', '=', 100)
                ->where('age', '>', 35)
                ->get();
Enter fullscreen mode Exit fullscreen mode

For convenience, if you want to verify that a column is = to a given value, you may pass the value as the second argument to the where method. Laravel will assume you would like to use the = operator:

$users = DB::table('users')->where('votes', 100)->get();
Enter fullscreen mode Exit fullscreen mode

As previously mentioned, you may use any operator that is supported by your database system:

$users = DB::table('users')
                ->where('votes', '>=', 100)
                ->get();

$users = DB::table('users')
                ->where('votes', '<>', 100)
                ->get();

$users = DB::table('users')
                ->where('name', 'like', 'T%')
                ->get();
Enter fullscreen mode Exit fullscreen mode

You may also pass an array of conditions to the where function. Each element of the array should be an array containing the three arguments typically passed to the where method:

$users = DB::table('users')->where([
    ['status', '=', '1'],
    ['subscribed', '<>', '1'],
])->get();
Enter fullscreen mode Exit fullscreen mode

PDO does not support binding column names. Therefore, you should never allow user input to dictate the column names referenced by your queries, including "order by" columns.

Or Where Clauses
When chaining together calls to the query builder's where method, the "where" clauses will be joined together using the and operator. However, you may use the orWhere method to join a clause to the query using the or operator. The orWhere method accepts the same arguments as the where method:

$users = DB::table('users')
                    ->where('votes', '>', 100)
                    ->orWhere('name', 'John')
                    ->get();
Enter fullscreen mode Exit fullscreen mode

If you need to group an "or" condition within parentheses, you may pass a closure as the first argument to the orWhere method:

$users = DB::table('users')
            ->where('votes', '>', 100)
            ->orWhere(function($query) {
                $query->where('name', 'Abigail')
                      ->where('votes', '>', 50);
            })
            ->get();
Enter fullscreen mode Exit fullscreen mode

The example above will produce the following SQL:

select * from users where votes > 100 or (name = 'Abigail' and votes > 50)
Enter fullscreen mode Exit fullscreen mode

You should always group orWhere calls in order to avoid unexpected behavior when global scopes are applied.

Where Not Clauses
The whereNot and orWhereNot methods may be used to negate a given group of query constraints. For example, the following query excludes products that are on clearance or which have a price that is less than ten:

$products = DB::table('products')
                ->whereNot(function ($query) {
                    $query->where('clearance', true)
                          ->orWhere('price', '<', 10);
                })
                ->get();
Enter fullscreen mode Exit fullscreen mode

JSON Where Clauses
Laravel also supports querying JSON column types on databases that provide support for JSON column types. Currently, this includes MySQL 5.7+, PostgreSQL, SQL Server 2016, and SQLite 3.9.0 (with the JSON1 extension). To query a JSON column, use the -> operator:

$users = DB::table('users')
                ->where('preferences->dining->meal', 'salad')
                ->get();
Enter fullscreen mode Exit fullscreen mode

You may use whereJsonContains to query JSON arrays. This feature is not supported by SQLite database versions less than 3.38.0:

$users = DB::table('users')
                ->whereJsonContains('options->languages', 'en')
                ->get();
Enter fullscreen mode Exit fullscreen mode

If your application uses the MySQL or PostgreSQL databases, you may pass an array of values to the whereJsonContains method:

$users = DB::table('users')
                ->whereJsonContains('options->languages', ['en', 'de'])
                ->get();
Enter fullscreen mode Exit fullscreen mode

You may use whereJsonLength method to query JSON arrays by their length:

$users = DB::table('users')
                ->whereJsonLength('options->languages', 0)
                ->get();
Enter fullscreen mode Exit fullscreen mode
$users = DB::table('users')
                ->whereJsonLength('options->languages', '>', 1)
                ->get();
Enter fullscreen mode Exit fullscreen mode

Additional Where Clauses
whereBetween / orWhereBetween

The whereBetween method verifies that a column's value is between two values:

$users = DB::table('users')
           ->whereBetween('votes', [1, 100])
           ->get();
Enter fullscreen mode Exit fullscreen mode

whereNotBetween / orWhereNotBetween

The whereNotBetween method verifies that a column's value lies outside of two values:

$users = DB::table('users')
                    ->whereNotBetween('votes', [1, 100])
                    ->get();
Enter fullscreen mode Exit fullscreen mode

whereBetweenColumns / whereNotBetweenColumns / orWhereBetweenColumns / orWhereNotBetweenColumns

The whereBetweenColumns method verifies that a column's value is between the two values of two columns in the same table row:

$patients = DB::table('patients')
                       ->whereBetweenColumns('weight', ['minimum_allowed_weight', 'maximum_allowed_weight'])
                       ->get();
Enter fullscreen mode Exit fullscreen mode

The whereNotBetweenColumns method verifies that a column's value lies outside the two values of two columns in the same table row:

$patients = DB::table('patients')
                       ->whereNotBetweenColumns('weight', ['minimum_allowed_weight', 'maximum_allowed_weight'])
                       ->get();
Enter fullscreen mode Exit fullscreen mode

whereIn / whereNotIn / orWhereIn / orWhereNotIn

The whereIn method verifies that a given column's value is contained within the given array:

$users = DB::table('users')
                    ->whereIn('id', [1, 2, 3])
                    ->get();
Enter fullscreen mode Exit fullscreen mode

The whereNotIn method verifies that the given column's value is not contained in the given array:

$users = DB::table('users')
                    ->whereNotIn('id', [1, 2, 3])
                    ->get();
Enter fullscreen mode Exit fullscreen mode

If you are adding a large array of integer bindings to your query, the whereIntegerInRaw or whereIntegerNotInRaw methods may be used to greatly reduce your memory usage.

whereNull / whereNotNull / orWhereNull / orWhereNotNull

The whereNull method verifies that the value of the given column is NULL:

$users = DB::table('users')
                ->whereNull('updated_at')
                ->get();
Enter fullscreen mode Exit fullscreen mode

The whereNotNull method verifies that the column's value is not NULL:

$users = DB::table('users')
                ->whereNotNull('updated_at')
                ->get();
Enter fullscreen mode Exit fullscreen mode

whereDate / whereMonth / whereDay / whereYear / whereTime

The whereDate method may be used to compare a column's value against a date:

$users = DB::table('users')
                ->whereDate('created_at', '2016-12-31')
                ->get();
Enter fullscreen mode Exit fullscreen mode

The whereMonth method may be used to compare a column's value against a specific month:

$users = DB::table('users')
                ->whereMonth('created_at', '12')
                ->get();
Enter fullscreen mode Exit fullscreen mode

The whereDay method may be used to compare a column's value against a specific day of the month:

$users = DB::table('users')
                ->whereDay('created_at', '31')
                ->get();
Enter fullscreen mode Exit fullscreen mode

The whereYear method may be used to compare a column's value against a specific year:

$users = DB::table('users')
                ->whereYear('created_at', '2016')
                ->get();
Enter fullscreen mode Exit fullscreen mode

The whereTime method may be used to compare a column's value against a specific time:

$users = DB::table('users')
                ->whereTime('created_at', '=', '11:20:45')
                ->get();
Enter fullscreen mode Exit fullscreen mode

whereColumn / orWhereColumn

The whereColumn method may be used to verify that two columns are equal:

$users = DB::table('users')
                ->whereColumn('first_name', 'last_name')
                ->get();
Enter fullscreen mode Exit fullscreen mode

You may also pass a comparison operator to the whereColumn method:

$users = DB::table('users')
                ->whereColumn('updated_at', '>', 'created_at')
                ->get();
Enter fullscreen mode Exit fullscreen mode

You may also pass an array of column comparisons to the whereColumn method. These conditions will be joined using the and operator:

$users = DB::table('users')
                ->whereColumn([
                    ['first_name', '=', 'last_name'],
                    ['updated_at', '>', 'created_at'],
                ])->get();
Enter fullscreen mode Exit fullscreen mode

Logical Grouping
Sometimes you may need to group several "where" clauses within parentheses in order to achieve your query's desired logical grouping. In fact, you should generally always group calls to the orWhere method in parentheses in order to avoid unexpected query behavior. To accomplish this, you may pass a closure to the where method:

$users = DB::table('users')
           ->where('name', '=', 'John')
           ->where(function ($query) {
               $query->where('votes', '>', 100)
                     ->orWhere('title', '=', 'Admin');
           })
           ->get();
Enter fullscreen mode Exit fullscreen mode

As you can see, passing a closure into the where method instructs the query builder to begin a constraint group. The closure will receive a query builder instance which you can use to set the constraints that should be contained within the parenthesis group. The example above will produce the following SQL:

select * from users where name = 'John' and (votes > 100 or title = 'Admin')
Enter fullscreen mode Exit fullscreen mode

You should always group orWhere calls in order to avoid unexpected behavior when global scopes are applied.

Advanced Where Clauses
Where Exists Clauses
The whereExists method allows you to write "where exists" SQL clauses. The whereExists method accepts a closure which will receive a query builder instance, allowing you to define the query that should be placed inside of the "exists" clause:

$users = DB::table('users')
           ->whereExists(function ($query) {
               $query->select(DB::raw(1))
                     ->from('orders')
                     ->whereColumn('orders.user_id', 'users.id');
           })
           ->get();
Enter fullscreen mode Exit fullscreen mode

The query above will produce the following SQL:

select * from users
where exists (
    select 1
    from orders
    where orders.user_id = users.id
)
Enter fullscreen mode Exit fullscreen mode

Subquery Where Clauses
Sometimes you may need to construct a "where" clause that compares the results of a subquery to a given value. You may accomplish this by passing a closure and a value to the where method. For example, the following query will retrieve all users who have a recent "membership" of a given type;

use App\Models\User;

$users = User::where(function ($query) {
    $query->select('type')
        ->from('membership')
        ->whereColumn('membership.user_id', 'users.id')
        ->orderByDesc('membership.start_date')
        ->limit(1);
}, 'Pro')->get();
Enter fullscreen mode Exit fullscreen mode

Ordering, Grouping, Limit & Offset
Ordering
The orderBy Method
The orderBy method allows you to sort the results of the query by a given column. The first argument accepted by the orderBy method should be the column you wish to sort by, while the second argument determines the direction of the sort and may be either asc or desc:

$users = DB::table('users')
                ->orderBy('name', 'desc')
                ->get();
Enter fullscreen mode Exit fullscreen mode

To sort by multiple columns, you may simply invoke orderBy as many times as necessary:

$users = DB::table('users')
                ->orderBy('name', 'desc')
                ->orderBy('email', 'asc')
                ->get();
Enter fullscreen mode Exit fullscreen mode

The latest & oldest Methods
The latest and oldest methods allow you to easily order results by date. By default, the result will be ordered by the table's created_at column. Or, you may pass the column name that you wish to sort by:

$user = DB::table('users')
                ->latest()
                ->first();
Enter fullscreen mode Exit fullscreen mode

Random Ordering
The inRandomOrder method may be used to sort the query results randomly. For example, you may use this method to fetch a random user:

$randomUser = DB::table('users')
                ->inRandomOrder()
                ->first();
Enter fullscreen mode Exit fullscreen mode

Removing Existing Orderings
The reorder method removes all of the "order by" clauses that have previously been applied to the query:

$query = DB::table('users')->orderBy('name');

$unorderedUsers = $query->reorder()->get();
Enter fullscreen mode Exit fullscreen mode

You may pass a column and direction when calling the reorder method in order to remove all existing "order by" clauses and apply an entirely new order to the query:

$query = DB::table('users')->orderBy('name');

$usersOrderedByEmail = $query->reorder('email', 'desc')->get();
Enter fullscreen mode Exit fullscreen mode

Grouping
The groupBy & having Methods
As you might expect, the groupBy and having methods may be used to group the query results. The having method's signature is similar to that of the where method:

$users = DB::table('users')
                ->groupBy('account_id')
                ->having('account_id', '>', 100)
                ->get();
Enter fullscreen mode Exit fullscreen mode

You can use the havingBetween method to filter the results within a given range:

$report = DB::table('orders')
                ->selectRaw('count(id) as number_of_orders, customer_id')
                ->groupBy('customer_id')
                ->havingBetween('number_of_orders', [5, 15])
                ->get();
Enter fullscreen mode Exit fullscreen mode

You may pass multiple arguments to the groupBy method to group by multiple columns:

$users = DB::table('users')
                ->groupBy('first_name', 'status')
                ->having('account_id', '>', 100)
                ->get();
Enter fullscreen mode Exit fullscreen mode

To build more advanced having statements, see the havingRaw method.

Limit & Offset
The skip & take Methods
You may use the skip and take methods to limit the number of results returned from the query or to skip a given number of results in the query:

$users = DB::table('users')->skip(10)->take(5)->get();
Enter fullscreen mode Exit fullscreen mode

Alternatively, you may use the limit and offset methods. These methods are functionally equivalent to the take and skip methods, respectively:

$users = DB::table('users')
                ->offset(10)
                ->limit(5)
                ->get();
Enter fullscreen mode Exit fullscreen mode

Insert Statements
The query builder also provides an insert method that may be used to insert records into the database table. The insert method accepts an array of column names and values:

DB::table('users')->insert([
    'email' => 'kayla@example.com',
    'votes' => 0
]);
Enter fullscreen mode Exit fullscreen mode

You may insert several records at once by passing an array of arrays. Each array represents a record that should be inserted into the table:

DB::table('users')->insert([
    ['email' => 'picard@example.com', 'votes' => 0],
    ['email' => 'janeway@example.com', 'votes' => 0],
]);
Enter fullscreen mode Exit fullscreen mode

The insertOrIgnore method will ignore errors while inserting records into the database. When using this method, you should be aware that duplicate record errors will be ignored and other types of errors may also be ignored depending on the database engine. For example, insertOrIgnore will bypass MySQL's strict mode:

DB::table('users')->insertOrIgnore([
    ['id' => 1, 'email' => 'sisko@example.com'],
    ['id' => 2, 'email' => 'archer@example.com'],
]);
Enter fullscreen mode Exit fullscreen mode

The insertUsing method will insert new records into the table while using a subquery to determine the data that should be inserted:

DB::table('pruned_users')->insertUsing([
    'id', 'name', 'email', 'email_verified_at'
], DB::table('users')->select(
    'id', 'name', 'email', 'email_verified_at'
)->where('updated_at', '<=', now()->subMonth()));
Enter fullscreen mode Exit fullscreen mode

Auto-Incrementing IDs
If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:

$id = DB::table('users')->insertGetId(
    ['email' => 'john@example.com', 'votes' => 0]
);
Enter fullscreen mode Exit fullscreen mode

When using PostgreSQL the insertGetId method expects the auto-incrementing column to be named id. If you would like to retrieve the ID from a different "sequence", you may pass the column name as the second parameter to the insertGetId method.

Upserts
The upsert method will insert records that do not exist and update the records that already exist with new values that you may specify. The method's first argument consists of the values to insert or update, while the second argument lists the column(s) that uniquely identify records within the associated table. The method's third and final argument is an array of columns that should be updated if a matching record already exists in the database:

DB::table('flights')->upsert(
    [
        ['departure' => 'Oakland', 'destination' => 'San Diego', 'price' => 99],
        ['departure' => 'Chicago', 'destination' => 'New York', 'price' => 150]
    ],
    ['departure', 'destination'],
    ['price']
);
Enter fullscreen mode Exit fullscreen mode

In the example above, Laravel will attempt to insert two records. If a record already exists with the same departure and destination column values, Laravel will update that record's price column.

All databases except SQL Server require the columns in the second argument of the upsert method to have a "primary" or "unique" index. In addition, the MySQL database driver ignores the second argument of the upsert method and always uses the "primary" and "unique" indexes of the table to detect existing records.

Update Statements
In addition to inserting records into the database, the query builder can also update existing records using the update method. The update method, like the insert method, accepts an array of column and value pairs indicating the columns to be updated. The update method returns the number of affected rows. You may constrain the update query using where clauses:

$affected = DB::table('users')
              ->where('id', 1)
              ->update(['votes' => 1]);
Enter fullscreen mode Exit fullscreen mode

Update Or Insert
Sometimes you may want to update an existing record in the database or create it if no matching record exists. In this scenario, the updateOrInsert method may be used. The updateOrInsert method accepts two arguments: an array of conditions by which to find the record, and an array of column and value pairs indicating the columns to be updated.

The updateOrInsert method will attempt to locate a matching database record using the first argument's column and value pairs. If the record exists, it will be updated with the values in the second argument. If the record can not be found, a new record will be inserted with the merged attributes of both arguments:

DB::table('users')
    ->updateOrInsert(
        ['email' => 'john@example.com', 'name' => 'John'],
        ['votes' => '2']
    );
Enter fullscreen mode Exit fullscreen mode

Updating JSON Columns
When updating a JSON column, you should use -> syntax to update the appropriate key in the JSON object. This operation is supported on MySQL 5.7+ and PostgreSQL 9.5+:

$affected = DB::table('users')
              ->where('id', 1)
              ->update(['options->enabled' => true]);
Enter fullscreen mode Exit fullscreen mode

Increment & Decrement
The query builder also provides convenient methods for incrementing or decrementing the value of a given column. Both of these methods accept at least one argument: the column to modify. A second argument may be provided to specify the amount by which the column should be incremented or decremented:

DB::table('users')->increment('votes');

DB::table('users')->increment('votes', 5);

DB::table('users')->decrement('votes');

DB::table('users')->decrement('votes', 5);
Enter fullscreen mode Exit fullscreen mode

You may also specify additional columns to update during the operation:

DB::table('users')->increment('votes', 1, ['name' => 'John']);
Enter fullscreen mode Exit fullscreen mode

Delete Statements
The query builder's delete method may be used to delete records from the table. The delete method returns the number of affected rows. You may constrain delete statements by adding "where" clauses before calling the delete method:

$deleted = DB::table('users')->delete();
Enter fullscreen mode Exit fullscreen mode
$deleted = DB::table('users')->where('votes', '>', 100)->delete();
Enter fullscreen mode Exit fullscreen mode

If you wish to truncate an entire table, which will remove all records from the table and reset the auto-incrementing ID to zero, you may use the truncate method:

DB::table('users')->truncate();
Enter fullscreen mode Exit fullscreen mode

Table Truncation & PostgreSQL
When truncating a PostgreSQL database, the CASCADE behavior will be applied. This means that all foreign key related records in other tables will be deleted as well.

Pessimistic Locking
The query builder also includes a few functions to help you achieve "pessimistic locking" when executing your select statements. To execute a statement with a "shared lock", you may call the sharedLock method. A shared lock prevents the selected rows from being modified until your transaction is committed:

DB::table('users')
        ->where('votes', '>', 100)
        ->sharedLock()
        ->get();
Enter fullscreen mode Exit fullscreen mode

Alternatively, you may use the lockForUpdate method. A "for update" lock prevents the selected records from being modified or from being selected with another shared lock:

DB::table('users')
        ->where('votes', '>', 100)
        ->lockForUpdate()
        ->get();
Enter fullscreen mode Exit fullscreen mode

Debugging
You may use the dd and dump methods while building a query to dump the current query bindings and SQL. The dd method will display the debug information and then stop executing the request. The dump method will display the debug information but allow the request to continue executing:

DB::table('users')->where('votes', '>', 100)->dd();

DB::table('users')->where('votes', '>', 100)->dump();
Enter fullscreen mode Exit fullscreen mode

whereId and whereEmail
Image description

Image description

https://laravel.com/docs/9.x/queries
QUERY BUILDER
1.Retrieving All Rows From A Table
2.Retrieving A Single Row / Column From A Table
3.Retrieving A List Of Column Values
4.count total no of table in table
5.find avg value of price field
6.find max value of price fiels

  1. find sum of all price
  2. count total no of different status where status is not equal to 1 9.join multiple table
  3. retrive all rows from table where no of votes greater than 100 and name is john 11.retrive all rows from table where no of votes greater than 100 or name is john
  4. .retrive all rows from table where no of votes is between 1 to 100
  5. retrive all rows from table where no of votes must be 100 and age greater than 35
  6. retrive all rows from table where name starts from T 15 retrive all rows from table where name should be asendin and email should be desending order
  7. retrive 5 row after skipping first 10 rows
  8. retrive first 5 row in table
  9. how to update or insert data 20.how to update data with where condtion 21 how to delete data
  10. how to delete data with where condition
  11. how to insert data with where condition

Image description

Image description
Image description
Image description

Image description

Image description

LARAVEL cheatsheet

Image description

Important Question and Links

  1. crud using laravel
  2. crud using laravel with ajax
  3. Laravel File Upload
  4. insert,update,Delete Multiple Records using Checkbox in Laravel
  5. https://www.javatpoint.com/import-and-export-csv-file-in-laravel-5-8
  6. Generate PDF from html view file and download using dompdf in Laravel
  7. how to send single and multiple email using laravel
  8. How to Create Multiple role-based users in Laravel Application
  9. How to display a table in a Verticle or Horizontal form in the Laravel PHP Framework
  10. How to Use Dropdown Search Functionality with Pagination in Laravel PHP Framework?
  11. How to Store Countries, States, Cities seed classes into the Database in Laravel PHP?
  12. Create Laravel multiple upload images and Displaying on view
  13. how to filter iput type and dropdown in laravel perform two crud using larvel and do following operation (i) total no of rows display (ii) show reently stored single data (iii) combine two table some data using left join

https://www.devopsschool.com/blog/how-to-create-multiple-role-based-users-in-laravel-application/
https://www.devopsschool.com/blog/how-to-display-a-table-in-a-verticle-or-horizontal-form-in-the-laravel-php-framework-part-1/
https://www.devopsschool.com/blog/how-to-display-a-table-in-a-verticle-or-horizontal-form-in-the-laravel-php-framework-part-2/
https://www.devopsschool.com/blog/simple-ajax-crud-application-in-laravel/
https://www.devopsschool.com/blog/how-to-delete-multiple-records-using-checkbox-in-laravel/
https://www.devopsschool.com/blog/how-to-use-dropdown-search-functionality-with-pagination-in-laravel-php-framework/
https://www.devopsschool.com/blog/crud-operations-in-laravel-php-framework/
https://www.devopsschool.com/blog/how-to-store-countries-states-cities-seed-classes-into-the-database-in-laravel-php-part-3/
https://www.devopsschool.com/blog/create-laravel-multiple-upload-images-and-displaying-on-view/

Top comments (0)