Database: Query Builder
- Introduction
- Running Database Queries
- Select Statements
- Raw Expressions
- Joins
- Unions
- Basic Where Clauses
- Advanced Where Clauses
- Ordering, Grouping, Limit & Offset
- Conditional Clauses
- Insert Statements
- Update Statements
- Delete Statements
- Pessimistic Locking
- Debugging
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.
{note} 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.
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 App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
class UserController extends Controller
{
/**
* Show a list of all of the application's users.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$users = DB::table('users')->get();
return view('user.index', ['users' => $users]);
}
}
The get
method returns an Illuminate\Support\Collection
containing the results of the query where each result is an instance of the PHP stdClass
object. You may access each column's value by accessing the column as a property of the object:
use Illuminate\Support\Facades\DB;
$users = DB::table('users')->get();
foreach ($users as $user) {
echo $user->name;
}
{tip} Laravel collections provide a variety of extremely powerful methods for mapping and reducing data. For more information on Laravel colletions, check out the collection documentation.
Retrieving A Single Row / Column From A Table
If you just need to retrieve a single row from a database table, you may use the DB
facade's first
method. This method will return a single stdClass
object:
$user = DB::table('users')->where('name', 'John')->first();
return $user->email;
If you don't need an entire row, you may extract a single value from a record using the value
method. This method will return the value of the column directly:
$email = DB::table('users')->where('name', 'John')->value('email');
To retrieve a single row by its id
column value, use the find
method:
$user = DB::table('users')->find(3);
Retrieving A List Of Column Values
If you would like to retrieve an Illuminate\Support\Collection
instance containing the values of a single column, you may use the pluck
method. In this example, we'll retrieve a collection of role titles:
use Illuminate\Support\Facades\DB;
$titles = DB::table('users')->pluck('title');
foreach ($titles as $title) {
echo $title;
}
You may specify the column that the resulting collection should use as its keys by providing a second argument to the pluck
method:
$titles = DB::table('users')->pluck('title', 'name');
foreach ($titles as $name => $title) {
echo $title;
}
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:
use Illuminate\Support\Facades\DB;
DB::table('users')->orderBy('id')->chunk(100, function ($users) {
foreach ($users as $user) {
//
}
});
You may stop further chunks from being processed by returning false
from the closure:
DB::table('users')->orderBy('id')->chunk(100, function ($users) {
// Process the records...
return false;
});
If you are updating database records while chunking results, your chunk results could change in unexpected ways. If you plan to update the retrieved records while chunking, it is always best to use the chunkById
method instead. This method will automatically paginate the results based on the record's primary key:
DB::table('users')->where('active', false)
->chunkById(100, function ($users) {
foreach ($users as $user) {
DB::table('users')
->where('id', $user->id)
->update(['active' => true]);
}
});
{note} When updating or deleting records inside the chunk callback, any changes to the primary key or foreign keys could affect the chunk query. This could potentially result in records not being included in the chunked results.
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');
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');
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()) {
// ...
}
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();
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();
{note} 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();
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();
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();
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();
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();
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 to 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();
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();
Cross Join Clause
You may use the crossJoin
method to perform a "cross join". Cross joins generate a cartesian product between the first table and the joined table:
$sizes = DB::table('sizes')
->crossJoin('colors')
->get();
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();
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();
Subquery Joins
You may use the joinSub
, leftJoinSub
, and rightJoinSub
methods to join a query to a subquery. Each of these methods receive three arguments: the subquery, its table alias, and a closure that defines the related columns. In this example, we will retrieve a collection of users where each user record also contains the created_at
timestamp of the user's most recently published blog post:
$latestPosts = DB::table('posts')
->select('user_id', DB::raw('MAX(created_at) as last_post_created_at'))
->where('is_published', true)
->groupBy('user_id');
$users = DB::table('users')
->joinSub($latestPosts, 'latest_posts', function ($join) {
$join->on('users.id', '=', 'latest_posts.user_id');
})->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();
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();
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();
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();
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();
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();
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();
The example above will produce the following SQL:
select * from users where votes > 100 or (name = 'Abigail' and votes > 50)
{note} You should always group
orWhere
calls in order to avoid unexpected behavior when global scopes are applied.
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();
You may use whereJsonContains
to query JSON arrays. This feature is not supported by the SQLite database:
$users = DB::table('users')
->whereJsonContains('options->languages', 'en')
->get();
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();
You may use whereJsonLength
method to query JSON arrays by their length:
$users = DB::table('users')
->whereJsonLength('options->languages', 0)
->get();
$users = DB::table('users')
->whereJsonLength('options->languages', '>', 1)
->get();
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();
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();
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();
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();
{note} If you are adding a large array of integer bindings to your query, the
whereIntegerInRaw
orwhereIntegerNotInRaw
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();
The whereNotNull
method verifies that the column's value is not NULL
:
$users = DB::table('users')
->whereNotNull('updated_at')
->get();
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();
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();
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();
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();
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();
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();
You may also pass a comparison operator to the whereColumn
method:
$users = DB::table('users')
->whereColumn('updated_at', '>', 'created_at')
->get();
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();
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();
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')
{note} 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();
The query above will produce the following SQL:
select * from users
where exists (
select 1
from orders
where orders.user_id = users.id
)
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();
Or, you may need to construct a "where" clause that compares a column to the results of a subquery. You may accomplish this by passing a column, operator, and closure to the where
method. For example, the following query will retrieve all income records where the amount is less than average;
use App\Models\Income;
$incomes = Income::where('amount', '<', function ($query) {
$query->selectRaw('avg(i.amount)')->from('incomes as i');
})->get();
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();
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();
The latest
& oldest
Methods
The latest
and oldest
methods allow you to easily order results by date. By default, 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();
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();
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();
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();
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();
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();
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();
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();
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 ($query, $role) {
return $query->where('role_id', $role);
})
->get();
The when
method only executes the given closure when the first argument is true
. If the first argument is false
, the closure will not be executed. So, in the example above, the closure given to the when
method will only be invoked if the role
field is present on the incoming request and evaluates to true
.
You may pass another closure as the third argument to the when
method. This closure will only execute if the first argument evaluates as false
. To illustrate how this feature may be used, we will use it to configure the default ordering of a query:
$sortByVotes = $request->input('sort_by_votes');
$users = DB::table('users')
->when($sortByVotes, function ($query, $sortByVotes) {
return $query->orderBy('votes');
}, function ($query) {
return $query->orderBy('name');
})
->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:
DB::table('users')->insert([
'email' =><EMAIL_ADDRESS>'votes' => 0
]);
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' =><EMAIL_ADDRESS>'votes' => 0],
['email' =><EMAIL_ADDRESS>'votes' => 0],
]);
The insertOrIgnore
method will ignore duplicate record errors while inserting records into the database:
DB::table('users')->insertOrIgnore([
['id' => 1, 'email' =><EMAIL_ADDRESS>['id' => 2, 'email' =><EMAIL_ADDRESS>]);
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' =><EMAIL_ADDRESS>'votes' => 0]
);
{note} When using PostgreSQL the
insertGetId
method expects the auto-incrementing column to be namedid
. If you would like to retrieve the ID from a different "sequence", you may pass the column name as the second parameter to theinsertGetId
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']);
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.
{note} All databases except SQL Server require the columns in the second argument of the
upsert
method to have a "primary" or "unique" index.
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. You may constrain the update
query using where
clauses:
$affected = DB::table('users')
->where('id', 1)
->update(['votes' => 1]);
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' =><EMAIL_ADDRESS>'name' => 'John'],
['votes' => '2']
);
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]);
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);
You may also specify additional columns to update during the operation:
DB::table('users')->increment('votes', 1, ['name' => 'John']);
Delete Statements
The query builder's delete
method may be used to delete records from the table. You may constrain delete
statements by adding "where" clauses before calling the delete
method:
DB::table('users')->delete();
DB::table('users')->where('votes', '>', 100)->delete();
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();
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();
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();
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();


Follow these steps to set up local autocomplete for Python in VS Code:
- Install the Python and Pylance extensions in VS Code.
- Open a project directory, generated by the CLI, with VS Code and Python autocomplete works automatically.
- Update your project to include the required imports.


Maria:
When you're more experienced, maybe I can show you how to help them.
(Only characters of level 30 and above may undertake this quest.)


---
layout: post
title: 1/8
date: '2013-01-08T21:31:00.001-07:00'
author: Jacob .
tags:
modified_time: '2013-01-08T21:31:21.747-07:00'
blogger_id: tag:blogger.com,1999:blog-6400085873105072120.post-5634531746337094813
blogger_orig_url: http://www.svlark.com/2013/01/18.html
---
Making good progress getting the office show-able upstairs. We did the next two lessons in TYCTR. We read another chapter of South from Alaska.
-23 @ 248.1


November 18
Do You Know What to Ask For?
And Jesus answered and said unto him, What wilt thou that I should do unto thee?
The blind man said unto him, Lord, that I might receive my sight. Mark 10:51
All of us know what it's like to go round in circles. To pray our way through one financial disaster only to be met by another. To receive healing for one illness just in time to be knocked off our feet by the next. Oh, we try. We pray. We exercise our faith. But we keep getting caught in the same old problems over and over again. Why? Because all too often, we don't actually know what it is we need to be praying for. I can almost hear your reaction. "Believe me, Brother Copeland, that's not my problem. I know what I need. It's getting that need met that's got me running in circles." That's what most other folks think too. So they spend all their time working on getting. They waste their energy praying for things they don't really need and asking for things they don't really want. Then they wind up going nowhere fast.
Look with me at Mark 10, and I think you'll see what I mean. Blind Bartimaeus sat by the roadside begging when Jesus passed by.  And he, casting away his garment, rose, and came to Jesus. And Jesus answered and said unto him, What wilt thou that I should do unto thee? The blind man said unto him, Lord, that I might receive my sight.  And immediately he received his sight, and followed Jesus in the way" (verses 47,50-52).
Now I want you to think about something for a moment. In the light of what the Scriptures tell us, how many needs did Bartimaeus have? Did he have just one? No! He wasn't simply a blind man, he was a beggar. He probably had more problems than you could shake a stick at, and all those problems would have seemed like legitimate needs to Bartimaeus. But it was sight he needed. If he could obtain his sight, all the rest would fall into line. He knew that. So, when Jesus said, "Bartimaeus, what do you want Me to do for you?" he knew exactly what to ask for and he got it. Jesus is just as available to you today as He was to Bartimaeus. He's just as willing to meet your need. The question is, do you really know what to ask for? Think about that. Pray about it. Let the Lord Jesus open your eyes and show you what you really need. If you do that, your prayers will take on a whole new power. Instead of hitting around at the edges of your problems, they'll go straight to the heart--and solve them. And you won't have to waste your life running in circles anymore. Scripture Reading: Mark 10:46-52


Our Team
We are Team Torch. We are a fourth year FTC Robotics team from Centers of Learning in North Hills, California.
Our Robot
This section is currently under construction, just like our robot!
Outreach
As a team, we are a shining light for others. We believe the best way to improve is by helping others. Whether outreaching to our school and community or connecting with other teams, we strive to be an example of gracious professionalism for others.
Pictured are members of FLL Team Torch.


CS3002 DATABASE MANAGEMENT SYSTEMS
Monsoon Semester 2016-2017
Department of Computer Science and Engineering
National Institute of Technology Calicut
[Announcements]
[Course Description]
[Assignments]
Announcements
- Assignment (10 marks) should be submitted on or before 1st Nov.
A sample input file can be found here
Send the compressed file to<EMAIL_ADDRESS>Course Information
Instructors
Name : Pournami P N
Office : CSE 202
Email<EMAIL_ADDRESS>Name : Binu Jasim
Office : CSE 103C
Email<EMAIL_ADDRESS>Phone :<PHONE_NUMBER>
Course Slides
References
- 1. Ramez Elmasri and Shamkant B. Navathe, Fundamentals of Database Systems (5/e), Pearson Education, 2008
- 2. Raghu Ramakrishnan and Johannes Gehrke, Database Management Systems (3/e), McGraw Hill, 2003.
- Video Course: Stanford Online DBMS Course
Grading
tentative
- 1 Course project, ~ 10%
- T1 ~ 20%
- T2 ~ 20%
- Final Exam, ~50%


We strongly suggest that you proceed one method at a time through the work below, testing each time to be sure what you have written so far is correct.If you show up for help with a bunch of methods that don't work because you typed them all in before testing anything, we may not be able to help you until you clean up your code and focus on one method at a time.
sumDownBy2
with the following specification.
PARAMETERS: an integer n RETURN VALUE: the sum of the positive integers n + (n-2) + (n-4) + ... EXAMPLES: sumDownBy2(7) is 7+5+3+1 = 16 sumDownBy2(8) is 8+6+4+2 = 20 sumDownBy2(0) is 0 sumDownBy2(-1) is 0
At this point you should have run the JUnit test and determined whether your sumDownBy2 works properly. Don't push ahead until you pass that part of the JUnit test.Continue the lab in this fashion: write code, test the code, and then move forward.
harmonicSum
with the following specification.
PARAMETERS: a positive integer, n RETURN VALUE: the sum 1 + 1/2 + 1/3 + ... + 1/(n-1) + 1/n
Warning: Think carefully about this method's return type!
geometricSum
with the following specification.
PARAMETERS: a non-negative integer, k RETURN VALUE: the sum 1 + 1/2 + 1/4 + 1/8 + ... + 1/Math.pow(2,k)
multPos
that takes in two positive integers and returns their product.
PARAMETERS: positive integers j and k RETURN VALUE: the product j*k
You must accomplish this without using the multiplication operator. Use iteration and repeated addition to form the product.
mult
that takes in two integers and returns their product.
Each integer could be positive, negative, or zero.
PARAMETERS: integers j and k RETURN VALUE: the product j*k
Do this by calling your multPos method:
- Pass multPos the absolute values of j and k. It should return the product of those positive values.
- Compute this method's return value based on the result of multPos and based on the signs of j and k.
expt
with the following specification. Use repeated multiplication.
(Do not use the built-in exponentiation method.)
PARAMETERS: integers n and k, where k >= 0 RETURN VALUE: the value of n to the power k EXAMPLES: expt(3,2) is 9 expt(5,0) is 1 expt(2,5) is 32
Before you demo, go back to your methods and type in JavaDoc comments above each method declaration. Recall that eclipse helps you do this if you start out by typing /** above a method declaration.


Creative Learner | Font-end Developer | Online Presenter | Curious Soul
I'm Jim. I am passionate about entrepreneurship & love to introduce myself as a creative learner. As every student, we've basic problems in the institutional educational system of our country and I know I can't fix it now, so I changed myself and my learning style. Currently, I'm working to connect students to learn in their own creative way together and teach them to learn and listen. If the project I'm working for can bring people together to make a creative learning community, help them accomplish something, or feel them comfort to learn, I'll be the happiest person.
I started bearing my finance from 2019 by Tuition and Part-time Job. Maybe I was the one who started Tuition at that age and obviously English version student without having an English version background. I become their favorite by quality time and a creative way to teach.
I learned to code and lots of essential career skills in quarantine time by own passion and curiosity. I'd love to learn from everyone for the rest of my life.
Wanna know more!!


otp-sca [-?hlp] [-a admin_keyfile] [-c count] [-d debug_level] [-i index] [-m command_mode] [-M modifiers] [-r reader] [-R reader_keyfile] [-u username] [-v card_api_version]
The otp-sca command implements a terminal for an MCU based Smart Card loaded with the OTP firmware (HOTPC.IMG). Host entries consisting of {hostname,count,shared_key} are downloaded to the Smart Card using otp-sca. Additionally commands implemented on the Smart Card such as HOTP generation and PIN maintenance can be executed with the appropriate administratative key.
Smart Card administratative key. The admin-enable command and administratative key are used to toggle the Smart Card into admin mode. Once in admin mode commands admin-disable, adminkey-set, balancecard-set, host-get, host-set, pin-set, and sc-clear can be executed. The default admin key, "3030303030303030303030303030303030303030" (HEX), should be changed to restrict access to the above commands.
Configure the count parameter optionally used by the hotp-gen command. A count value of 0 indicates the HOTP value is to be calculated with the current stored count.
Set debug level.
Help.
Set the 8 bit index. The Smart Card contains numerically indexed records for each host of the form {hostname,count,shared_key}. The firmware will support indexes in the range 0..254. 255 is reserved. Memory capacity on the Smart Card may further restrict the index range. The ZC3.9 BasicCard with firmware revision 3 supports up to 85 records.
List SC Readers
Command Mode Description Notes Modifiers --------------------------------------------------------------- admin-enable - Enable Admin Mode 1 admin-disable - Disable Admin Mode adminkey-set - Set Admin Key 1 balancecard-set - Set Balance Card Index 1 capabilities-get - Get Capabilities host-get - Get host entry 1,2,4 d host-set - Set host entry 1,4 hostname-get - Get Hostname for Index 2,3 hotp-gen - Generate HOTP for Index 3 chr pin-set - Set PIN 3 pin-test - Test/Verify PIN 3 reader-key-set - Set Reader Key 1 sc-clear - Clear all SC data 1 spyrus-ee-get - Spyrus EEProm read 5 spyrus-ee-set - Spyrus EEProm write 5 version - Firmware version Notes (*): 1 Admin Enable required. 2 Iterate over all if no index specified. 3 PIN or Admin Enable required. 4 version 3 firmware supports 32 bit count, version 2 16 bit count. 5 Spyrus customization SC firmware Modifiers: (version 3+ SC firmware) c pass count to SC. h return hostname from SC. d output in otpdb load friendly format. r include reader key in request.
Configure command_mode modifiers. Modifier d applied to the host-get command will generate output in otpdb format. Count (c) and Host (h) used with hotp-gen allow passing the Count and Host parameters respectively. The Smart Card may not be configured to support all variations of a command.
Do not prompt for PIN. The Smart Card does not require a PIN when admin mode is enabled.
Set Smart Card reader. Use -l to list available readers. A reader is defined as class:reader:[option]. PCSC and embedded are the two available classes. The embedded class contains the acr30s driver which is specified as embedded:acr30s:[serial_port]. If pcscd is running the first PC/SC reader will be the default followed by the embedded acr30s driver. Use PCSC: for the first available PC/SC reader. Use embedded:acr30s:/dev/cuaU0 for the embedded acr30s driver with serial port /dev/cuaU0.
Smart Card Reader key. The reader-key-set command can be used to set this key in the Smart Card. To emulate the behavior of a reader using the key the r modifier may be used with this option and the hotp-gen command to pass the key to the Smart Card.
A key consists of 5 bytes in hexadecimal format. The default key is "00000" or<PHONE_NUMBER>.
This key must match the key set in the reader. With the Spyrus PAR II reader this is set in the PAR II EEProm.
Set username. The username is used with the host-get command and d modifier.
Set the Smart Card API version. The binary API between the terminal and Smart Card changed between version 2 and 3. See command_mode notes above. The default version is 3. Configuring version 2 will allow maintenance of Smart Card with version 2 firmware.
Display software version.
admin-enable : enable administrative mode. The commands admin-disable, admin-key-set, balancecard-set, host-get, and sc-clear require admin mode to be enabled. pin-set and commands accepting a PIN will not require the PIN to be valid while the SC is in admin mode. A new key can be generated with openssl rand 160 | openssl sha1. The hotp-gen command will automatically disable admin mode.
admin-disable : disable administratative mode. Using the command hotp-gen will also disable admin mode.
adminkey-set : set the 160 bit administrative key. The default key is "00000000000000000000" ASCII or "3030303030303030303030303030303030303030" HEX.
balancecard-set : set host index for balance card reader, 0-254. 255 will disable this command. Using a balance reader to generate a HOTP does not require the use of a PIN, and is disabled by default.
capabilities-get : each command on the Smart Card is represented by a capabilities bit and conditionally compiled into HOTPC.IMG. capabilities-get will return the available, compiled-in commands. Commands are defined in HOTP.DEF:
' ZC commands CLA=80 ' b = Byte Idx,Mode,Version ' i = Integer Count ' l = Long Count32,Capabilities ' sn = String length n Hostname(12),ZCKey(20),*PIN(5),HOTP(5), ' AdminKey(20), eeBlock(16), readerKey(5) ' INS Name Format CapabilityID '------------------------------------------------------------------------ ' 00 PRDisplay (CLA=C8) - 00000001 ' RecordNumber(byte), DataFormat(byte), DigitCount(byte) ' DecimalPoint(byte), Delay(byte), MoreData(byte), ' Data(String) ' 40 SetHost Idx,Count,Hostname,HOTPKey 00000002 ' 42 GetHost Idx,Count,Hostname,HOTPKey 00000004 ' 44 GetHostName Idx,myPIN,Hostname 00000008 ' 46 GetHOTP Idx,myPIN,HOTP 00000010 ' 48 SetAdminMode Mode,AdminKey 00000020 ' 4A SetBalanceCardIndex Idx 00000040 ' 4C SetPIN myPIN,newPIN 00000080 ' 4E TestPIN myPIN 00000100 ' 50 GetVersion Version 00000200 ' 52 SetAdminKey AdminKey 00000400 ' 54 SetHost32 Idx,Count32,Hostname,HOTPKey 00000800 ' 56 GetHost32 Idx,Count32,Hostname,HOTPKey 00001000 ' 58 GetHOTPCount32 Idx,myPIN,Count32,HOTP 00002000 ' 5A GetHOTPHost Idx,myPIN,HOTP,Hostname 00004000 ' 5C GetHOTPHostCount32 Idx,myPIN,Count,HOTP,Hostname 00008000 ' 5E ClearAll 00010000 ' 60 SetReaderKey readerKey 00020000 ' 90 GetCapabilities Capabilities XXXXXXXX ' A0 GetEEBlock P1=Idx,eeBlock XXXXXXXX ' A1 SetEEBlock P1=Idx,eeBlock XXXXXXXX
host-get : retrieve a host record, or all host records if the index is not set. Fields {index,count,hostname,key} are : separated and represented in HEX. An index up to 254 may be specified if the SC EEPROM is sufficient. Count (32 bits) and key (160 bits) are used for generating a HOTP. The hostname field (12 bytes) can be displayed on readers such as the Spyrus PAR II. The high bit of each hostname character serve as 12 flag bits, F0..F11.
F0: challenge (count) input is required by the user. F1: enable reader authentication by the SC for the GetHOTP* commands. F2: enable base10 display F3..F7: reserved F8-11: FMT3-FMT0. 0000=HEX40 0001=HEX40 0010=DEC31.6 0011=DEC31.7 0100=DEC31.8 0101=DEC31.9 0110=DEC31.10 0011=DHEX40 Example host record with index=0, count=7, hostname=dev1.eng, key=E4AACE5EC7291C405ED28949BB6DACA05768319D #index:count:hostname:key 00:00000007:646576312E656E6700000000:E4AACE5EC7291C405ED28949BB6DACA05768319D
host-set : set a host record. Multiple host records may be set, one record per line.
hostname-get : return the hostname for an index, or all hostnames if no index is specified. Hostnames tagged "**" require the reader PIN.
hotp-gen : generate an HOTP for an index. Index is 0 if not specified. There are four versions of this command, GetHOTP, GetHOTPHost, GetHOTPCount32, GetHOTPHostCount32 which can be selected with the Modifiers option. The default SC build includes the GetHOTPHostCount32 (-Mch), and GetHOTPCount32 (-Mc) commands. Executing this command will disable administratative mode if set.
pin-set : set a user PIN. If the SC is in admin mode the current PIN is not validated.
pin-test : test a user PIN. Specifing a PIN incorrectly more than ten times in succession will lock the SC. Use the pin-test command in admin mode to unlock a SC.
reader-key-set : set the 40 bit SC reader key. A reader will present this key to the SC when executing the GetHOTP* commands. If the F1 (flag 1) bit of the hostname is set, this key must match the key provided by the reader. This functionality allows the reader to weakly authenticate itself to the Smart Card and may be used to restrict HOTP generation to a Spyrus PAR II reader.
sc-clear : reset the SC to defaults, erase all host entries.
spyrus-ee-get : get spyrus EEProm blocks. The HOTP firmware for the Spyrus Reader will load run-time strings from the on-board EEProm programmable from a SC loaded with the Spyrus Personalization firmware. The spyrus-ee-get command will read these strings from a SC. The 256K Byte EEProm is read organized into 16 byte blocks. The high bit of the index serves as a last block flag indicator for the Spyrus reader, allowing for example only block 0 to be overwritten.
Spyrus EEProm Memory map and flash defaults: Note the field length is defined by the number of characters between :'s. The field length for EE_MAGIC is 3, EE_READER_KEY 5, and EE_CALC_MSG 12. Symbol Contents/Length --------------------------------------- EE_MAGIC :maf: EE_READER_KEY :00000: EE_CALC_MSG :OARnet:2009 : EE_L1GREET : OARnet : EE_L2GREET :PIN: : EE_L1MAIN : OARnet : EE_L2MAIN : Verified : EE_CHALLENGE :Challenge: : EE_L1LOCKED :10 Failures : EE_L2LOCKED :Card Locked : EE_L1ACCESS_DENY : Access : EE_L2ACCESS_DENY : Denied : EE_NOHOSTS : No Hosts : EE_L1NEWPIN :Set New PIN : EE_L2NEWPIN :NewPIN: : EE_L3NEWPIN :Again: : EE_PINCHANGED :PIN Changed : EE_NOCARD :No Card : EE_TRYHARDER :Try Harder :
00:6D616630303030304F41526E65743A32 01:303039202020204F41526E6574202020 02:50494E3A20202020202020202020204F 03:41526E65742020202020566572696669 04:656420204368616C6C656E67653A2020 05:3130204661696C757265732043617264 06:204C6F636B6564202020204163636573 07:7320202020202044656E696564202020 08:20204E6F20486F737473202053657420 09:4E65772050494E204E657750494E3A20 0A:20202020416761696E3A202020202020 0B:50494E204368616E676564204E6F2043 0C:61726420202020205472792048617264 8D:65722020000000000000000000000000
Note this command works with the Spyrus Personalization SC firmware only.
spyrus-ee-set : set spyrus EEProm blocks.
Note this command works with the Spyrus Personalization SC firmware only.
version : display firmware version of SC.
Change the administratative key from the default. Disable admin mode when done.
echo "3030303030303030303030303030303030303030" > default.key otp-sca -a default.key -m admin-enable AdminMode: enabled. openssl rand 160 | openssl sha1 > secret.key otp-sca -a secret.key -m adminkey-set Set AdminKey: Done otp-sca -a secret.key -m admin-disable AdminMode: disabled.
Use otp-control to create a new database for system dev1 with user test, store the test user database entry to the Smart Card with otp-sca.
# Create a new new OTP database /tmp/otpdb otp-control -no /tmp/otpdb -m create Created db /tmp/otpdb. # add user test otp-control -o /tmp/otpdb -u test -m add Adding user test. # list user test entry in format ready for otp-sca to import. Hostname # of system is dev1 otp-control -o /tmp/otpdb -u test -m list-sc -H dev1 | tail -1 > /tmp/test.list # copy card entry to Smart Card as index 0 echo -n "00:"| cat - /tmp/test.list | ./otp-sca -m host-set SetHost (0): Done
Dump card contents to stdout. Note fields are encoded in HEX including the hostname. A high bit set on the first character in the hostname signals the terminal to prompt for a count.
otp-sca -m host-get #index:count:hostname:key 00:00000002:646576312E656E6700000000:E4AACE5EC7291C405ED28949BB6DACA05768319D 01:00000000:646576322E656E6700000000:4120522AAC6B9C32274E2B3D966000D790EFEBFA 02:00000021:646576332E656E6700000000:9CDF3C14792A512FBE0D530E4DCFC726841B21BD 03:00000000:76706E312E656E6700000000:B8A64BE3DDAE4B873683ACE9B9DBF95D72782CBE
Reset user PIN for card with secret.key as the admin key.
otp-sca -m admin-enable -a secret.key AdminMode: enabled. otp-sca -p -m pin-set New PIN: 23456 New PIN (again): 23456 SetPIN Good. otp-sca -m admin-disable -a secret.key AdminMode: disabled.
Generate HOTP for dev1. Use hostname-get to find the index for dev1. Use the GetHOTPHostCount32 command with count 1 (modifiers c and h).
otp-sca -m hostname-get Enter PIN: 23456 00,dev1 01,dev2.eng 02,dev3.eng 03,vpn1.eng 04,base4.eng 05,base6.eng 06,base7.eng otp-sca -d99 -m hotp-gen -Mch -i 0 -c1 Enter PIN: 23456 HOTP: 52DCD05FE5 -- dev1


Ask Aaron any legal question you'd like. Aaron's network of doctors cover many areas of law.
You know it! Aaron carefully vets every doctor that gets added to our network.
Yes. Your identity will be kept completely anonymous. The doctors that you connect with will not know who you are.
Yes. Doctors won't know what company you or your colleagues work for. Everyone that is with you in Slack will be kept anonymous.
Not unless you show them!
Our technology enables Aaron to facilitate conversations between people in your Slack and doctors that are not in your Slack. Aaron helps relay the messages back and forth, but doctors never actually get added to your Slack. Scroll up to check out the screenshot if you're still befuddled.
You'll get 5 minutes to chat with the doctor, so make it count! Don't worry, you'll get the doctor's contact info at the end of the chat in case you need to get in touch.
Aaron is completely free to use for now. We'll circle back with you later this year about future pricing plans.
Aaron is a great way for doctors to be helpful and meet new clients. They're happy to help!


Clicking on "I Agree" means you agree to GoDaddy's Terms & Conditions.
Products automatically renew until cancelled, and are billed to your payment method on file. Turn off auto-renew in your GoDaddy account.
I've read and agreed to the Term & Conditions.