0% found this document useful (0 votes)
13 views9 pages

Digital Security

Lectures

Uploaded by

ttooffee23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views9 pages

Digital Security

Lectures

Uploaded by

ttooffee23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Database and Query Builder

# Introduction
Laravel's database query builder provides a convenient, fluent interface to creating and
running database queries. It can be used to perform most database operations in your
application and works perfectly with all of Laravel's supported database systems.
The Laravel query builder uses PDO parameter binding to protect your application against
SQL injection attacks. There is no need to clean or sanitize strings passed to the query builder
as query bindings.
# Running Database Queries
Retrieving All Rows from a Table
You may use the table method provided by the DB facade to begin a query. The table method
returns a fluent query builder instance for the given table, allowing you to chain more
constraints onto the query and then finally retrieve the results of the query using the get
method:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;
class UserController extends Controller
{
/**
* Show a list of all of the application's users.
*/
public function index(): View
{
$users = DB::table('users')->get();
return view('user.index', ['users' => $users]);
}
}
Chunking Results
If you need to work with thousands of database records, consider using the chunk method
provided by the DB facade. 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:

1
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
DB::table('users')->orderBy('id')->chunk(100, function (Collection $users) {
foreach ($users as $user) {
// ...
}
});
Streaming Results Lazily
The lazy method works similarly to the chunk method in the sense that it executes the query
in chunks. However, instead of passing each chunk into a callback, the lazy() method returns
a LazyCollection, which lets you interact with the results as a single stream:
use Illuminate\Support\Facades\DB;
DB::table('users')->orderBy('id')->lazy()->each(function (object $user) {
// ...
});
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');
# Select Statements
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();
# 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')

2
->select(DB::raw('count(*) as user_count, status'))
->where('status', '<>', 1)
->groupBy('status')
->get();
# Joins
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();
# 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();
# 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.
$users = DB::table('users')
3
->where('votes', '=', 100)
->where('age', '>', 35)
->get();
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();
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 (Builder $query) {
$query->where('clearance', true)
->orWhere('price', '<', 10);
})
->get();
Where Any / All / None Clauses
Sometimes you may need to apply the same query constraints to multiple columns. For
example, you may want to retrieve all records where any columns in a given list are LIKE a
given value. You may accomplish this using the whereAny method:
$users = DB::table('users')
->where('active', true)
->whereAny([
'name',
'email',
'phone',
], 'like', 'Example%')

4
->get();
JSON Where Clauses
Laravel also supports querying JSON column types on databases that provide support for
JSON column types. Currently, this includes MariaDB 10.3+, MySQL 8.0+, PostgreSQL
12.0+, SQL Server 2017+, and SQLite 3.39.0+. To query a JSON column, use the -> operator:
$users = DB::table('users')
->where('preferences->dining->meal', 'salad')
->get();
You may use whereJsonContains to query JSON arrays:
$users = DB::table('users')
->whereJsonContains('options->languages', 'en')
->get();
Additional Where Clauses
The whereLike method allows you to add "LIKE" clauses to your query for pattern matching.
These methods provide a database-agnostic way of performing string matching queries, with
the ability to toggle case-sensitivity. By default, string matching is case-insensitive:
$users = DB::table('users')
->whereLike('name', '%John%')
->get();
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 (Builder $query) {
$query->where('votes', '>', 100)
->orWhere('title', '=', 'Admin');
})
->get();

5
# 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 (Builder $query) {
$query->select(DB::raw(1))
->from('orders')
->whereColumn('orders.user_id', 'users.id');
})
->get();
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;
use Illuminate\Database\Query\Builder;
$users = User::where(function (Builder $query) {
$query->select('type')
->from('membership')
->whereColumn('membership.user_id', 'users.id')
->orderByDesc('membership.start_date')
->limit(1);
}, 'Pro')->get();
Full Text Where Clauses
The whereFullText and orWhereFullText methods may be used to add full text "where" clauses
to a query for columns that have full text indexes. These methods will be transformed into the
appropriate SQL for the underlying database system by Laravel. For example, a MATCH
AGAINST clause will be generated for applications utilizing MariaDB or MySQL:
$users = DB::table('users')
->whereFullText('bio', 'web developer')

6
->get();
# Ordering, Grouping, Limit and Offset
Ordering
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();
Grouping
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();
Limit and Offset
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();
# Conditional Clauses
Sometimes you may want certain query clauses to apply to a query based on another condition.
For instance, you may only want to apply a where statement if a given input value is present
on the incoming HTTP request. You may accomplish this using the when method:
$role = $request->input('role');
$users = DB::table('users')
->when($role, function (Builder $query, string $role) {
$query->where('role_id', $role);
})
->get();
# 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:

7
DB::table('users')->insert([
'email' => '[email protected]',
'votes' => 0
]);
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']
);
# 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]);
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 MariaDB 10.3+, MySQL 5.7+, and PostgreSQL
9.5+:
$affected = DB::table('users')
->where('id', 1)
->update(['options->enabled' => true]);

8
Increment and 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);
# 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();
$deleted = DB::table('users')->where('votes', '>', 100)->delete();
# 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();
# 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();

You might also like