From c65795b9e41e3420adb71fd02e6c5e96db567632 Mon Sep 17 00:00:00 2001 From: Andrew Brown Date: Fri, 14 Feb 2025 11:11:38 -0600 Subject: [PATCH] remove arbitrary chaining alignment use a single indent for chains on a new line, rather than trying to align it with some arbitrary pattern in the first line. this arbitrary alignment very easily gets out of sync as changes occur to the code, and often times the adjustments are not made to the chained alignment. the single indent alignment does not suffer this problem. this is to bring us in line with https://github.com/laravel/framework/pull/53835 and https://github.com/laravel/framework/pull/53748 this commit only contains whitespace changes. if accepted, I will make these adjustments to the remaining docs pages. --- billing.md | 40 ++-- eloquent-factories.md | 170 +++++++------- eloquent-relationships.md | 56 ++--- http-client.md | 16 +- http-tests.md | 74 +++--- queries.md | 466 +++++++++++++++++++------------------- validation.md | 4 +- 7 files changed, 413 insertions(+), 413 deletions(-) diff --git a/billing.md b/billing.md index 294f6827856..d7dabcdbb45 100644 --- a/billing.md +++ b/billing.md @@ -842,8 +842,8 @@ The amount of time a customer has to pay their invoice before their subscription If you would like to set a specific [quantity](https://stripe.com/docs/billing/subscriptions/quantities) for the price when creating the subscription, you should invoke the `quantity` method on the subscription builder before creating the subscription: $user->newSubscription('default', 'price_monthly') - ->quantity(5) - ->create($paymentMethod); + ->quantity(5) + ->create($paymentMethod); #### Additional Details @@ -862,14 +862,14 @@ If you would like to specify additional [customer](https://stripe.com/docs/api/c If you would like to apply a coupon when creating the subscription, you may use the `withCoupon` method: $user->newSubscription('default', 'price_monthly') - ->withCoupon('code') - ->create($paymentMethod); + ->withCoupon('code') + ->create($paymentMethod); Or, if you would like to apply a [Stripe promotion code](https://stripe.com/docs/billing/subscriptions/discounts/codes), you may use the `withPromotionCode` method: $user->newSubscription('default', 'price_monthly') - ->withPromotionCode('promo_code_id') - ->create($paymentMethod); + ->withPromotionCode('promo_code_id') + ->create($paymentMethod); The given promotion code ID should be the Stripe API ID assigned to the promotion code and not the customer facing promotion code. If you need to find a promotion code ID based on a given customer facing promotion code, you may use the `findPromotionCode` method: @@ -1104,8 +1104,8 @@ If the customer is on trial, the trial period will be maintained. Additionally, If you would like to swap prices and cancel any trial period the customer is currently on, you may invoke the `skipTrial` method: $user->subscription('default') - ->skipTrial() - ->swap('price_yearly'); + ->skipTrial() + ->swap('price_yearly'); If you would like to swap prices and immediately invoice the customer instead of waiting for their next billing cycle, you may use the `swapAndInvoice` method: @@ -1237,8 +1237,8 @@ If you want to swap a single price on a subscription, you may do so using the `s $user = User::find(1); $user->subscription('default') - ->findItemOrFail('price_basic') - ->swap('price_pro'); + ->findItemOrFail('price_basic') + ->swap('price_pro'); #### Proration @@ -1329,9 +1329,9 @@ To start using usage billing, you will first need to create a new product in you You may also start a metered subscription via [Stripe Checkout](#checkout): $checkout = Auth::user() - ->newSubscription('default', []) - ->meteredPrice('price_metered') - ->checkout(); + ->newSubscription('default', []) + ->meteredPrice('price_metered') + ->checkout(); return view('your-checkout-view', [ 'checkout' => $checkout, @@ -1441,8 +1441,8 @@ By default, the billing cycle anchor is the date the subscription was created or $anchor = Carbon::parse('first day of next month'); $request->user()->newSubscription('default', 'price_monthly') - ->anchorBillingCycleOn($anchor->startOfDay()) - ->create($request->paymentMethodId); + ->anchorBillingCycleOn($anchor->startOfDay()) + ->create($request->paymentMethodId); // ... }); @@ -1507,8 +1507,8 @@ If you would like to offer trial periods to your customers while still collectin Route::post('/user/subscribe', function (Request $request) { $request->user()->newSubscription('default', 'price_monthly') - ->trialDays(10) - ->create($request->paymentMethodId); + ->trialDays(10) + ->create($request->paymentMethodId); // ... }); @@ -1523,8 +1523,8 @@ The `trialUntil` method allows you to provide a `DateTime` instance that specifi use Carbon\Carbon; $user->newSubscription('default', 'price_monthly') - ->trialUntil(Carbon::now()->addDays(10)) - ->create($paymentMethod); + ->trialUntil(Carbon::now()->addDays(10)) + ->create($paymentMethod); You may determine if a user is within their trial period using either the `onTrial` method of the user instance or the `onTrial` method of the subscription instance. The two examples below are equivalent: @@ -2131,7 +2131,7 @@ First, you could redirect your customer to the dedicated payment confirmation pa try { $subscription = $user->newSubscription('default', 'price_monthly') - ->create($paymentMethod); + ->create($paymentMethod); } catch (IncompletePayment $exception) { return redirect()->route( 'cashier.payment', diff --git a/eloquent-factories.md b/eloquent-factories.md index 9baefc19b37..dd315a8ff34 100644 --- a/eloquent-factories.md +++ b/eloquent-factories.md @@ -267,12 +267,12 @@ Sometimes you may wish to alternate the value of a given model attribute for eac use Illuminate\Database\Eloquent\Factories\Sequence; $users = User::factory() - ->count(10) - ->state(new Sequence( - ['admin' => 'Y'], - ['admin' => 'N'], - )) - ->create(); + ->count(10) + ->state(new Sequence( + ['admin' => 'Y'], + ['admin' => 'N'], + )) + ->create(); In this example, five users will be created with an `admin` value of `Y` and five users will be created with an `admin` value of `N`. @@ -281,28 +281,28 @@ If necessary, you may include a closure as a sequence value. The closure will be use Illuminate\Database\Eloquent\Factories\Sequence; $users = User::factory() - ->count(10) - ->state(new Sequence( - fn (Sequence $sequence) => ['role' => UserRoles::all()->random()], - )) - ->create(); + ->count(10) + ->state(new Sequence( + fn (Sequence $sequence) => ['role' => UserRoles::all()->random()], + )) + ->create(); Within a sequence closure, you may access the `$index` or `$count` properties on the sequence instance that is injected into the closure. The `$index` property contains the number of iterations through the sequence that have occurred thus far, while the `$count` property contains the total number of times the sequence will be invoked: $users = User::factory() - ->count(10) - ->sequence(fn (Sequence $sequence) => ['name' => 'Name '.$sequence->index]) - ->create(); + ->count(10) + ->sequence(fn (Sequence $sequence) => ['name' => 'Name '.$sequence->index]) + ->create(); For convenience, sequences may also be applied using the `sequence` method, which simply invokes the `state` method internally. The `sequence` method accepts a closure or arrays of sequenced attributes: $users = User::factory() - ->count(2) - ->sequence( - ['name' => 'First User'], - ['name' => 'Second User'], - ) - ->create(); + ->count(2) + ->sequence( + ['name' => 'First User'], + ['name' => 'Second User'], + ) + ->create(); ## Factory Relationships @@ -316,26 +316,26 @@ Next, let's explore building Eloquent model relationships using Laravel's fluent use App\Models\User; $user = User::factory() - ->has(Post::factory()->count(3)) - ->create(); + ->has(Post::factory()->count(3)) + ->create(); By convention, when passing a `Post` model to the `has` method, Laravel will assume that the `User` model must have a `posts` method that defines the relationship. If necessary, you may explicitly specify the name of the relationship that you would like to manipulate: $user = User::factory() - ->has(Post::factory()->count(3), 'posts') - ->create(); + ->has(Post::factory()->count(3), 'posts') + ->create(); Of course, you may perform state manipulations on the related models. In addition, you may pass a closure based state transformation if your state change requires access to the parent model: $user = User::factory() - ->has( - Post::factory() - ->count(3) - ->state(function (array $attributes, User $user) { - return ['user_type' => $user->type]; - }) - ) - ->create(); + ->has( + Post::factory() + ->count(3) + ->state(function (array $attributes, User $user) { + return ['user_type' => $user->type]; + }) + ) + ->create(); #### Using Magic Methods @@ -343,24 +343,24 @@ Of course, you may perform state manipulations on the related models. In additio For convenience, you may use Laravel's magic factory relationship methods to build relationships. For example, the following example will use convention to determine that the related models should be created via a `posts` relationship method on the `User` model: $user = User::factory() - ->hasPosts(3) - ->create(); + ->hasPosts(3) + ->create(); When using magic methods to create factory relationships, you may pass an array of attributes to override on the related models: $user = User::factory() - ->hasPosts(3, [ - 'published' => false, - ]) - ->create(); + ->hasPosts(3, [ + 'published' => false, + ]) + ->create(); You may provide a closure based state transformation if your state change requires access to the parent model: $user = User::factory() - ->hasPosts(3, function (array $attributes, User $user) { - return ['user_type' => $user->type]; - }) - ->create(); + ->hasPosts(3, function (array $attributes, User $user) { + return ['user_type' => $user->type]; + }) + ->create(); ### Belongs To Relationships @@ -371,20 +371,20 @@ Now that we have explored how to build "has many" relationships using factories, use App\Models\User; $posts = Post::factory() - ->count(3) - ->for(User::factory()->state([ - 'name' => 'Jessica Archer', - ])) - ->create(); + ->count(3) + ->for(User::factory()->state([ + 'name' => 'Jessica Archer', + ])) + ->create(); If you already have a parent model instance that should be associated with the models you are creating, you may pass the model instance to the `for` method: $user = User::factory()->create(); $posts = Post::factory() - ->count(3) - ->for($user) - ->create(); + ->count(3) + ->for($user) + ->create(); #### Using Magic Methods @@ -392,11 +392,11 @@ If you already have a parent model instance that should be associated with the m For convenience, you may use Laravel's magic factory relationship methods to define "belongs to" relationships. For example, the following example will use convention to determine that the three posts should belong to the `user` relationship on the `Post` model: $posts = Post::factory() - ->count(3) - ->forUser([ - 'name' => 'Jessica Archer', - ]) - ->create(); + ->count(3) + ->forUser([ + 'name' => 'Jessica Archer', + ]) + ->create(); ### Many to Many Relationships @@ -407,8 +407,8 @@ Like [has many relationships](#has-many-relationships), "many to many" relations use App\Models\User; $user = User::factory() - ->has(Role::factory()->count(3)) - ->create(); + ->has(Role::factory()->count(3)) + ->create(); #### Pivot Table Attributes @@ -419,33 +419,33 @@ If you need to define attributes that should be set on the pivot / intermediate use App\Models\User; $user = User::factory() - ->hasAttached( - Role::factory()->count(3), - ['active' => true] - ) - ->create(); + ->hasAttached( + Role::factory()->count(3), + ['active' => true] + ) + ->create(); You may provide a closure based state transformation if your state change requires access to the related model: $user = User::factory() - ->hasAttached( - Role::factory() - ->count(3) - ->state(function (array $attributes, User $user) { - return ['name' => $user->name.' Role']; - }), - ['active' => true] - ) - ->create(); + ->hasAttached( + Role::factory() + ->count(3) + ->state(function (array $attributes, User $user) { + return ['name' => $user->name.' Role']; + }), + ['active' => true] + ) + ->create(); If you already have model instances that you would like to be attached to the models you are creating, you may pass the model instances to the `hasAttached` method. In this example, the same three roles will be attached to all three users: $roles = Role::factory()->count(3)->create(); $user = User::factory() - ->count(3) - ->hasAttached($roles, ['active' => true]) - ->create(); + ->count(3) + ->hasAttached($roles, ['active' => true]) + ->create(); #### Using Magic Methods @@ -453,10 +453,10 @@ If you already have model instances that you would like to be attached to the mo For convenience, you may use Laravel's magic factory relationship methods to define many to many relationships. For example, the following example will use convention to determine that the related models should be created via a `roles` relationship method on the `User` model: $user = User::factory() - ->hasRoles(1, [ - 'name' => 'Editor' - ]) - ->create(); + ->hasRoles(1, [ + 'name' => 'Editor' + ]) + ->create(); ### Polymorphic Relationships @@ -485,17 +485,17 @@ Polymorphic "many to many" (`morphToMany` / `morphedByMany`) relationships may b use App\Models\Video; $videos = Video::factory() - ->hasAttached( - Tag::factory()->count(3), - ['public' => true] - ) - ->create(); + ->hasAttached( + Tag::factory()->count(3), + ['public' => true] + ) + ->create(); Of course, the magic `has` method may also be used to create polymorphic "many to many" relationships: $videos = Video::factory() - ->hasTags(3, ['public' => true]) - ->create(); + ->hasTags(3, ['public' => true]) + ->create(); ### Defining Relationships Within Factories diff --git a/eloquent-relationships.md b/eloquent-relationships.md index f4ed21b32d8..86435c293b9 100644 --- a/eloquent-relationships.md +++ b/eloquent-relationships.md @@ -185,8 +185,8 @@ Once the relationship method has been defined, we can access the [collection](/d Since all relationships also serve as query builders, you may add further constraints to the relationship query by calling the `comments` method and continuing to chain conditions onto the query: $comment = Post::find(1)->comments() - ->where('title', 'foo') - ->first(); + ->where('title', 'foo') + ->first(); Like the `hasOne` method, you may also override the foreign and local keys by passing additional arguments to the `hasMany` method: @@ -740,8 +740,8 @@ As noted previously, attributes from the intermediate table may be accessed on m For example, if your application contains users that may subscribe to podcasts, you likely have a many-to-many relationship between users and podcasts. If this is the case, you may wish to rename your intermediate table attribute to `subscription` instead of `pivot`. This can be done using the `as` method when defining the relationship: return $this->belongsToMany(Podcast::class) - ->as('subscription') - ->withTimestamps(); + ->as('subscription') + ->withTimestamps(); Once the custom intermediate table attribute has been specified, you may access the intermediate table data using the customized name: @@ -757,29 +757,29 @@ Once the custom intermediate table attribute has been specified, you may access You can also filter the results returned by `belongsToMany` relationship queries using the `wherePivot`, `wherePivotIn`, `wherePivotNotIn`, `wherePivotBetween`, `wherePivotNotBetween`, `wherePivotNull`, and `wherePivotNotNull` methods when defining the relationship: return $this->belongsToMany(Role::class) - ->wherePivot('approved', 1); + ->wherePivot('approved', 1); return $this->belongsToMany(Role::class) - ->wherePivotIn('priority', [1, 2]); + ->wherePivotIn('priority', [1, 2]); return $this->belongsToMany(Role::class) - ->wherePivotNotIn('priority', [1, 2]); + ->wherePivotNotIn('priority', [1, 2]); return $this->belongsToMany(Podcast::class) - ->as('subscriptions') - ->wherePivotBetween('created_at', ['2020-01-01 00:00:00', '2020-12-31 00:00:00']); + ->as('subscriptions') + ->wherePivotBetween('created_at', ['2020-01-01 00:00:00', '2020-12-31 00:00:00']); return $this->belongsToMany(Podcast::class) - ->as('subscriptions') - ->wherePivotNotBetween('created_at', ['2020-01-01 00:00:00', '2020-12-31 00:00:00']); + ->as('subscriptions') + ->wherePivotNotBetween('created_at', ['2020-01-01 00:00:00', '2020-12-31 00:00:00']); return $this->belongsToMany(Podcast::class) - ->as('subscriptions') - ->wherePivotNull('expired_at'); + ->as('subscriptions') + ->wherePivotNull('expired_at'); return $this->belongsToMany(Podcast::class) - ->as('subscriptions') - ->wherePivotNotNull('expired_at'); + ->as('subscriptions') + ->wherePivotNotNull('expired_at'); ### Ordering Queries via Intermediate Table Columns @@ -787,8 +787,8 @@ You can also filter the results returned by `belongsToMany` relationship queries You can order the results returned by `belongsToMany` relationship queries using the `orderByPivot` method. In the following example, we will retrieve all of the latest badges for the user: return $this->belongsToMany(Badge::class) - ->where('rank', 'gold') - ->orderByPivot('created_at', 'desc'); + ->where('rank', 'gold') + ->orderByPivot('created_at', 'desc'); ### Defining Custom Intermediate Table Models @@ -1354,11 +1354,11 @@ In most situations, you should use [logical groups](/docs/{{version}}/queries#lo use Illuminate\Database\Eloquent\Builder; $user->posts() - ->where(function (Builder $query) { - return $query->where('active', 1) - ->orWhere('votes', '>=', 100); - }) - ->get(); + ->where(function (Builder $query) { + return $query->where('active', 1) + ->orWhere('votes', '>=', 100); + }) + ->get(); The example above will produce the following SQL. Note that the logical grouping has properly grouped the constraints and the query remains constrained to a specific user: @@ -1505,8 +1505,8 @@ You may occasionally need to add query constraints based on the "type" of the re Sometimes you may want to query for the children of a "morph to" relationship's parent. You may accomplish this using the `whereMorphedTo` and `whereNotMorphedTo` methods, which will automatically determine the proper morph type mapping for the given model. These methods accept the name of the `morphTo` relationship as their first argument and the related parent model as their second argument: $comments = Comment::whereMorphedTo('commentable', $post) - ->orWhereMorphedTo('commentable', $video) - ->get(); + ->orWhereMorphedTo('commentable', $video) + ->get(); #### Querying All Related Models @@ -1581,8 +1581,8 @@ If you need to set additional query constraints on the count query, you may pass If you're combining `withCount` with a `select` statement, ensure that you call `withCount` after the `select` method: $posts = Post::select(['title', 'body']) - ->withCount('comments') - ->get(); + ->withCount('comments') + ->get(); ### Other Aggregate Functions @@ -1614,8 +1614,8 @@ Like the `loadCount` method, deferred versions of these methods are also availab If you're combining these aggregate methods with a `select` statement, ensure that you call the aggregate methods after the `select` method: $posts = Post::select(['title', 'body']) - ->withExists('comments') - ->get(); + ->withExists('comments') + ->get(); ### Counting Related Models on Morph To Relationships diff --git a/http-client.md b/http-client.md index 34b8396c730..9970fa34c88 100644 --- a/http-client.md +++ b/http-client.md @@ -565,9 +565,9 @@ Sometimes you may need to specify that a single URL should return a series of fa Http::fake([ // Stub a series of responses for GitHub endpoints... 'github.com/*' => Http::sequence() - ->push('Hello World', 200) - ->push(['foo' => 'bar'], 200) - ->pushStatus(404), + ->push('Hello World', 200) + ->push(['foo' => 'bar'], 200) + ->pushStatus(404), ]); When all the responses in a response sequence have been consumed, any further requests will cause the response sequence to throw an exception. If you would like to specify a default response that should be returned when a sequence is empty, you may use the `whenEmpty` method: @@ -575,16 +575,16 @@ When all the responses in a response sequence have been consumed, any further re Http::fake([ // Stub a series of responses for GitHub endpoints... 'github.com/*' => Http::sequence() - ->push('Hello World', 200) - ->push(['foo' => 'bar'], 200) - ->whenEmpty(Http::response()), + ->push('Hello World', 200) + ->push(['foo' => 'bar'], 200) + ->whenEmpty(Http::response()), ]); If you would like to fake a sequence of responses but do not need to specify a specific URL pattern that should be faked, you may use the `Http::fakeSequence` method: Http::fakeSequence() - ->push('Hello World', 200) - ->whenEmpty(Http::response()); + ->push('Hello World', 200) + ->whenEmpty(Http::response()); #### Fake Callback diff --git a/http-tests.md b/http-tests.md index 4bb481f31e8..3826c0e994b 100644 --- a/http-tests.md +++ b/http-tests.md @@ -225,8 +225,8 @@ test('an action that requires authentication', function () { $user = User::factory()->create(); $response = $this->actingAs($user) - ->withSession(['banned' => false]) - ->get('/'); + ->withSession(['banned' => false]) + ->get('/'); // }); @@ -247,8 +247,8 @@ class ExampleTest extends TestCase $user = User::factory()->create(); $response = $this->actingAs($user) - ->withSession(['banned' => false]) - ->get('/'); + ->withSession(['banned' => false]) + ->get('/'); // } @@ -450,7 +450,7 @@ test('making an api request', function () { ->assertStatus(201) ->assertJson([ 'created' => true, - ]); + ]); }); ``` @@ -595,11 +595,11 @@ test('fluent json', function () { $response ->assertJson(fn (AssertableJson $json) => $json->where('id', 1) - ->where('name', 'Victoria Faith') - ->where('email', fn (string $email) => str($email)->is('victoria@gmail.com')) - ->whereNot('status', 'pending') - ->missing('password') - ->etc() + ->where('name', 'Victoria Faith') + ->where('email', fn (string $email) => str($email)->is('victoria@gmail.com')) + ->whereNot('status', 'pending') + ->missing('password') + ->etc() ); }); ``` @@ -617,11 +617,11 @@ public function test_fluent_json(): void $response ->assertJson(fn (AssertableJson $json) => $json->where('id', 1) - ->where('name', 'Victoria Faith') - ->where('email', fn (string $email) => str($email)->is('victoria@gmail.com')) - ->whereNot('status', 'pending') - ->missing('password') - ->etc() + ->where('name', 'Victoria Faith') + ->where('email', fn (string $email) => str($email)->is('victoria@gmail.com')) + ->whereNot('status', 'pending') + ->missing('password') + ->etc() ); } ``` @@ -641,21 +641,21 @@ To assert that an attribute is present or absent, you may use the `has` and `mis $response->assertJson(fn (AssertableJson $json) => $json->has('data') - ->missing('message') + ->missing('message') ); In addition, the `hasAll` and `missingAll` methods allow asserting the presence or absence of multiple attributes simultaneously: $response->assertJson(fn (AssertableJson $json) => $json->hasAll(['status', 'data']) - ->missingAll(['message', 'code']) + ->missingAll(['message', 'code']) ); You may use the `hasAny` method to determine if at least one of a given list of attributes is present: $response->assertJson(fn (AssertableJson $json) => $json->has('status') - ->hasAny('data', 'message', 'code') + ->hasAny('data', 'message', 'code') ); @@ -672,13 +672,13 @@ In these situations, we may use the fluent JSON object's `has` method to make as $response ->assertJson(fn (AssertableJson $json) => $json->has(3) - ->first(fn (AssertableJson $json) => + ->first(fn (AssertableJson $json) => $json->where('id', 1) - ->where('name', 'Victoria Faith') - ->where('email', fn (string $email) => str($email)->is('victoria@gmail.com')) - ->missing('password') - ->etc() - ) + ->where('name', 'Victoria Faith') + ->where('email', fn (string $email) => str($email)->is('victoria@gmail.com')) + ->missing('password') + ->etc() + ) ); @@ -698,14 +698,14 @@ When testing these routes, you may use the `has` method to assert against the nu $response ->assertJson(fn (AssertableJson $json) => $json->has('meta') - ->has('users', 3) - ->has('users.0', fn (AssertableJson $json) => + ->has('users', 3) + ->has('users.0', fn (AssertableJson $json) => $json->where('id', 1) - ->where('name', 'Victoria Faith') - ->where('email', fn (string $email) => str($email)->is('victoria@gmail.com')) - ->missing('password') - ->etc() - ) + ->where('name', 'Victoria Faith') + ->where('email', fn (string $email) => str($email)->is('victoria@gmail.com')) + ->missing('password') + ->etc() + ) ); However, instead of making two separate calls to the `has` method to assert against the `users` collection, you may make a single call which provides a closure as its third parameter. When doing so, the closure will automatically be invoked and scoped to the first item in the collection: @@ -713,13 +713,13 @@ However, instead of making two separate calls to the `has` method to assert agai $response ->assertJson(fn (AssertableJson $json) => $json->has('meta') - ->has('users', 3, fn (AssertableJson $json) => + ->has('users', 3, fn (AssertableJson $json) => $json->where('id', 1) - ->where('name', 'Victoria Faith') - ->where('email', fn (string $email) => str($email)->is('victoria@gmail.com')) - ->missing('password') - ->etc() - ) + ->where('name', 'Victoria Faith') + ->where('email', fn (string $email) => str($email)->is('victoria@gmail.com')) + ->missing('password') + ->etc() + ) ); diff --git a/queries.md b/queries.md index 8971f52d3da..8852b192c8c 100644 --- a/queries.md +++ b/queries.md @@ -219,8 +219,8 @@ The query builder also provides a variety of methods for retrieving aggregate va 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'); + ->where('finalized', 1) + ->avg('price'); #### Determining if Records Exist @@ -246,8 +246,8 @@ You may not always want to select all columns from a database table. Using the ` use Illuminate\Support\Facades\DB; $users = DB::table('users') - ->select('name', 'email as user_email') - ->get(); + ->select('name', 'email as user_email') + ->get(); The `distinct` method allows you to force the query to return distinct results: @@ -265,10 +265,10 @@ If you already have a query builder instance and you wish to add a column to its 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(); + ->select(DB::raw('count(*) as user_count, status')) + ->where('status', '<>', 1) + ->groupBy('status') + ->get(); > [!WARNING] > Raw statements will be injected into the query as strings, so you should be extremely careful to avoid creating SQL injection vulnerabilities. @@ -284,8 +284,8 @@ Instead of using the `DB::raw` method, you may also use the following methods to 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(); + ->selectRaw('price * ? as price_with_tax', [1.0825]) + ->get(); #### `whereRaw / orWhereRaw` @@ -293,8 +293,8 @@ The `selectRaw` method can be used in place of `addSelect(DB::raw(/* ... */))`. 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(); + ->whereRaw('price > IF(state = "TX", ?, 100)', [200]) + ->get(); #### `havingRaw / orHavingRaw` @@ -302,10 +302,10 @@ The `whereRaw` and `orWhereRaw` methods can be used to inject a raw "where" clau 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(); + ->select('department', DB::raw('SUM(price) as total_sales')) + ->groupBy('department') + ->havingRaw('SUM(price) > ?', [2500]) + ->get(); #### `orderByRaw` @@ -313,8 +313,8 @@ The `havingRaw` and `orHavingRaw` methods may be used to provide a raw string as 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(); + ->orderByRaw('updated_at - created_at DESC') + ->get(); ### `groupByRaw` @@ -322,9 +322,9 @@ The `orderByRaw` method may be used to provide a raw string as the value of the 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(); + ->select('city', 'state') + ->groupByRaw('city, state') + ->get(); ## Joins @@ -337,10 +337,10 @@ The query builder may also be used to add join clauses to your queries. To perfo 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(); + ->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 @@ -348,12 +348,12 @@ The query builder may also be used to add join clauses to your queries. To perfo 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(); + ->leftJoin('posts', 'users.id', '=', 'posts.user_id') + ->get(); $users = DB::table('users') - ->rightJoin('posts', 'users.id', '=', 'posts.user_id') - ->get(); + ->rightJoin('posts', 'users.id', '=', 'posts.user_id') + ->get(); #### Cross Join Clause @@ -361,8 +361,8 @@ If you would like to perform a "left join" or "right join" instead of an "inner 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(); + ->crossJoin('colors') + ->get(); #### Advanced Join Clauses @@ -370,19 +370,19 @@ You may use the `crossJoin` method to perform a "cross join". Cross joins genera 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 (JoinClause $join) { - $join->on('users.id', '=', 'contacts.user_id')->orOn(/* ... */); - }) - ->get(); + ->join('contacts', function (JoinClause $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 (JoinClause $join) { - $join->on('users.id', '=', 'contacts.user_id') - ->where('contacts.user_id', '>', 5); - }) - ->get(); + ->join('contacts', function (JoinClause $join) { + $join->on('users.id', '=', 'contacts.user_id') + ->where('contacts.user_id', '>', 5); + }) + ->get(); #### Subquery Joins @@ -390,14 +390,14 @@ If you would like to use a "where" clause on your joins, you may use the `where` You may use the `joinSub`, `leftJoinSub`, and `rightJoinSub` methods to join a query to a subquery. Each of these methods receives 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'); + ->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 (JoinClause $join) { - $join->on('users.id', '=', 'latest_posts.user_id'); - })->get(); + ->joinSub($latestPosts, 'latest_posts', function (JoinClause $join) { + $join->on('users.id', '=', 'latest_posts.user_id'); + })->get(); #### Lateral Joins @@ -410,14 +410,14 @@ You may use the `joinLateral` and `leftJoinLateral` methods to perform a "latera In this example, we will retrieve a collection of users as well as the user's three most recent blog posts. Each user can produce up to three rows in the result set: one for each of their most recent blog posts. The join condition is specified with a `whereColumn` clause within the subquery, referencing the current user row: $latestPosts = DB::table('posts') - ->select('id as post_id', 'title as post_title', 'created_at as post_created_at') - ->whereColumn('user_id', 'users.id') - ->orderBy('created_at', 'desc') - ->limit(3); + ->select('id as post_id', 'title as post_title', 'created_at as post_created_at') + ->whereColumn('user_id', 'users.id') + ->orderBy('created_at', 'desc') + ->limit(3); $users = DB::table('users') - ->joinLateral($latestPosts, 'latest_posts') - ->get(); + ->joinLateral($latestPosts, 'latest_posts') + ->get(); ## Unions @@ -427,12 +427,12 @@ The query builder also provides a convenient method to "union" two or more queri use Illuminate\Support\Facades\DB; $first = DB::table('users') - ->whereNull('first_name'); + ->whereNull('first_name'); $users = DB::table('users') - ->whereNull('last_name') - ->union($first) - ->get(); + ->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. @@ -447,9 +447,9 @@ You may use the query builder's `where` method to add "where" clauses to the que 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(); + ->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: @@ -458,16 +458,16 @@ For convenience, if you want to verify that a column is `=` to a given value, yo As previously mentioned, you may use any operator that is supported by your database system: $users = DB::table('users') - ->where('votes', '>=', 100) - ->get(); + ->where('votes', '>=', 100) + ->get(); $users = DB::table('users') - ->where('votes', '<>', 100) - ->get(); + ->where('votes', '<>', 100) + ->get(); $users = DB::table('users') - ->where('name', 'like', 'T%') - ->get(); + ->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: @@ -488,19 +488,19 @@ You may also pass an array of conditions to the `where` function. Each element o 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('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 (Builder $query) { - $query->where('name', 'Abigail') - ->where('votes', '>', 50); - }) - ->get(); + ->where('votes', '>', 100) + ->orWhere(function (Builder $query) { + $query->where('name', 'Abigail') + ->where('votes', '>', 50); + }) + ->get(); The example above will produce the following SQL: @@ -517,11 +517,11 @@ select * from users where votes > 100 or (name = 'Abigail' and votes > 50) 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(); + ->whereNot(function (Builder $query) { + $query->where('clearance', true) + ->orWhere('price', '<', 10); + }) + ->get(); ### Where Any / All / None Clauses @@ -529,13 +529,13 @@ The `whereNot` and `orWhereNot` methods may be used to negate a given group of q 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%') - ->get(); + ->where('active', true) + ->whereAny([ + 'name', + 'email', + 'phone', + ], 'like', 'Example%') + ->get(); The query above will result in the following SQL: @@ -552,12 +552,12 @@ WHERE active = true AND ( Similarly, the `whereAll` method may be used to retrieve records where all of the given columns match a given constraint: $posts = DB::table('posts') - ->where('published', true) - ->whereAll([ - 'title', - 'content', - ], 'like', '%Laravel%') - ->get(); + ->where('published', true) + ->whereAll([ + 'title', + 'content', + ], 'like', '%Laravel%') + ->get(); The query above will result in the following SQL: @@ -573,13 +573,13 @@ WHERE published = true AND ( The `whereNone` method may be used to retrieve records where none of the given columns match a given constraint: $posts = DB::table('albums') - ->where('published', true) - ->whereNone([ - 'title', - 'lyrics', - 'tags', - ], 'like', '%explicit%') - ->get(); + ->where('published', true) + ->whereNone([ + 'title', + 'lyrics', + 'tags', + ], 'like', '%explicit%') + ->get(); The query above will result in the following SQL: @@ -599,30 +599,30 @@ WHERE published = true AND NOT ( 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(); + ->where('preferences->dining->meal', 'salad') + ->get(); You may use `whereJsonContains` to query JSON arrays: $users = DB::table('users') - ->whereJsonContains('options->languages', 'en') - ->get(); + ->whereJsonContains('options->languages', 'en') + ->get(); If your application uses the MariaDB, 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(); + ->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(); + ->whereJsonLength('options->languages', 0) + ->get(); $users = DB::table('users') - ->whereJsonLength('options->languages', '>', 1) - ->get(); + ->whereJsonLength('options->languages', '>', 1) + ->get(); ### Additional Where Clauses @@ -632,34 +632,34 @@ You may use `whereJsonLength` method to query JSON arrays by their length: 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(); + ->whereLike('name', '%John%') + ->get(); You can enable a case-sensitive search via the `caseSensitive` argument: $users = DB::table('users') - ->whereLike('name', '%John%', caseSensitive: true) - ->get(); + ->whereLike('name', '%John%', caseSensitive: true) + ->get(); The `orWhereLike` method allows you to add an "or" clause with a LIKE condition: $users = DB::table('users') - ->where('votes', '>', 100) - ->orWhereLike('name', '%John%') - ->get(); + ->where('votes', '>', 100) + ->orWhereLike('name', '%John%') + ->get(); The `whereNotLike` method allows you to add "NOT LIKE" clauses to your query: $users = DB::table('users') - ->whereNotLike('name', '%John%') - ->get(); + ->whereNotLike('name', '%John%') + ->get(); Similarly, you can use `orWhereNotLike` to add an "or" clause with a NOT LIKE condition: $users = DB::table('users') - ->where('votes', '>', 100) - ->orWhereNotLike('name', '%John%') - ->get(); + ->where('votes', '>', 100) + ->orWhereNotLike('name', '%John%') + ->get(); > [!WARNING] > The `whereLike` case-sensitive search option is currently not supported on SQL Server. @@ -669,22 +669,22 @@ Similarly, you can use `orWhereNotLike` to add an "or" clause with a NOT LIKE co 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(); + ->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(); + ->whereNotIn('id', [1, 2, 3]) + ->get(); You may also provide a query object as the `whereIn` method's second argument: $activeUsers = DB::table('users')->select('id')->where('is_active', 1); $users = DB::table('comments') - ->whereIn('user_id', $activeUsers) - ->get(); + ->whereIn('user_id', $activeUsers) + ->get(); The example above will produce the following SQL: @@ -704,144 +704,144 @@ select * from comments where user_id in ( The `whereBetween` method verifies that a column's value is between two values: $users = DB::table('users') - ->whereBetween('votes', [1, 100]) - ->get(); + ->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(); + ->whereNotBetween('votes', [1, 100]) + ->get(); **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(); + ->whereBetweenColumns('weight', ['minimum_allowed_weight', 'maximum_allowed_weight']) + ->get(); 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(); + ->whereNotBetweenColumns('weight', ['minimum_allowed_weight', 'maximum_allowed_weight']) + ->get(); **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(); + ->whereNull('updated_at') + ->get(); The `whereNotNull` method verifies that the column's value is not `NULL`: $users = DB::table('users') - ->whereNotNull('updated_at') - ->get(); + ->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(); + ->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(); + ->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(); + ->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(); + ->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(); + ->whereTime('created_at', '=', '11:20:45') + ->get(); **wherePast / whereFuture / whereToday / whereBeforeToday / whereAfterToday** The `wherePast` and `whereFuture` methods may be used to determine if a column's value is in the past or future: $invoices = DB::table('invoices') - ->wherePast('due_at') - ->get(); + ->wherePast('due_at') + ->get(); $invoices = DB::table('invoices') - ->whereFuture('due_at') - ->get(); + ->whereFuture('due_at') + ->get(); The `whereNowOrPast` and `whereNowOrFuture` methods may be used to determine if a column's value is in the past or future, inclusive of the current date and time: $invoices = DB::table('invoices') - ->whereNowOrPast('due_at') - ->get(); + ->whereNowOrPast('due_at') + ->get(); $invoices = DB::table('invoices') - ->whereNowOrFuture('due_at') - ->get(); + ->whereNowOrFuture('due_at') + ->get(); The `whereToday`, `whereBeforeToday`, and `whereAfterToday` methods may be used to determine if a column's value is today, before today, or after today, respectively: $invoices = DB::table('invoices') - ->whereToday('due_at') - ->get(); + ->whereToday('due_at') + ->get(); $invoices = DB::table('invoices') - ->whereBeforeToday('due_at') - ->get(); + ->whereBeforeToday('due_at') + ->get(); $invoices = DB::table('invoices') - ->whereAfterToday('due_at') - ->get(); + ->whereAfterToday('due_at') + ->get(); Similarly, the `whereTodayOrBefore` and `whereTodayOrAfter` methods may be used to determine if a column's value is before today or after today, inclusive of today's date: $invoices = DB::table('invoices') - ->whereTodayOrBefore('due_at') - ->get(); + ->whereTodayOrBefore('due_at') + ->get(); $invoices = DB::table('invoices') - ->whereTodayOrAfter('due_at') - ->get(); + ->whereTodayOrAfter('due_at') + ->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(); + ->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(); + ->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(); + ->whereColumn([ + ['first_name', '=', 'last_name'], + ['updated_at', '>', 'created_at'], + ])->get(); ### Logical Grouping @@ -849,12 +849,12 @@ You may also pass an array of column comparisons to the `whereColumn` method. Th 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(); + ->where('name', '=', 'John') + ->where(function (Builder $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: @@ -874,22 +874,22 @@ select * from users where name = 'John' and (votes > 100 or title = 'Admin') 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(); + ->whereExists(function (Builder $query) { + $query->select(DB::raw(1)) + ->from('orders') + ->whereColumn('orders.user_id', 'users.id'); + }) + ->get(); Alternatively, you may provide a query object to the `whereExists` method instead of a closure: $orders = DB::table('orders') - ->select(DB::raw(1)) - ->whereColumn('orders.user_id', 'users.id'); + ->select(DB::raw(1)) + ->whereColumn('orders.user_id', 'users.id'); $users = DB::table('users') - ->whereExists($orders) - ->get(); + ->whereExists($orders) + ->get(); Both of the examples above will produce the following SQL: @@ -936,8 +936,8 @@ Or, you may need to construct a "where" clause that compares a column to the res The `whereFullText` and `orWhereFullText` methods may be used to add full text "where" clauses to a query for columns that have [full text indexes](/docs/{{version}}/migrations#available-index-types). 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') - ->get(); + ->whereFullText('bio', 'web developer') + ->get(); ## Ordering, Grouping, Limit and Offset @@ -951,15 +951,15 @@ The `whereFullText` and `orWhereFullText` methods may be used to add full text " 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(); + ->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(); + ->orderBy('name', 'desc') + ->orderBy('email', 'asc') + ->get(); #### The `latest` and `oldest` Methods @@ -967,8 +967,8 @@ To sort by multiple columns, you may simply invoke `orderBy` as many times as ne 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(); + ->latest() + ->first(); #### Random Ordering @@ -976,8 +976,8 @@ The `latest` and `oldest` methods allow you to easily order results by date. By 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(); + ->inRandomOrder() + ->first(); #### Removing Existing Orderings @@ -1003,24 +1003,24 @@ You may pass a column and direction when calling the `reorder` method in order t 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(); + ->groupBy('account_id') + ->having('account_id', '>', 100) + ->get(); 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(); + ->selectRaw('count(id) as number_of_orders, customer_id') + ->groupBy('customer_id') + ->havingBetween('number_of_orders', [5, 15]) + ->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(); + ->groupBy('first_name', 'status') + ->having('account_id', '>', 100) + ->get(); To build more advanced `having` statements, see the [`havingRaw`](#raw-methods) method. @@ -1037,9 +1037,9 @@ You may use the `skip` and `take` methods to limit the number of results returne 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(); + ->offset(10) + ->limit(5) + ->get(); ## Conditional Clauses @@ -1049,10 +1049,10 @@ Sometimes you may want certain query clauses to apply to a query based on anothe $role = $request->input('role'); $users = DB::table('users') - ->when($role, function (Builder $query, string $role) { - $query->where('role_id', $role); - }) - ->get(); + ->when($role, function (Builder $query, string $role) { + $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`. @@ -1061,12 +1061,12 @@ You may pass another closure as the third argument to the `when` method. This cl $sortByVotes = $request->boolean('sort_by_votes'); $users = DB::table('users') - ->when($sortByVotes, function (Builder $query, bool $sortByVotes) { - $query->orderBy('votes'); - }, function (Builder $query) { - $query->orderBy('name'); - }) - ->get(); + ->when($sortByVotes, function (Builder $query, bool $sortByVotes) { + $query->orderBy('votes'); + }, function (Builder $query) { + $query->orderBy('name'); + }) + ->get(); ## Insert Statements @@ -1175,8 +1175,8 @@ DB::table('users')->updateOrInsert( 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]); + ->where('id', 1) + ->update(['options->enabled' => true]); ### Increment and Decrement @@ -1217,16 +1217,16 @@ The query builder's `delete` method may be used to delete records from the table 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(); + ->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(); + ->where('votes', '>', 100) + ->lockForUpdate() + ->get(); While not obligatory, it is recommended to wrap pessimistic locks within a [transaction](/docs/{{version}}/database#database-transactions). This ensures that the data retrieved remains unaltered in the database until the entire operation completes. In case of a failure, the transaction will roll back any changes and release the locks automatically: diff --git a/validation.md b/validation.md index fd2d1df26ed..41d2a521afa 100644 --- a/validation.md +++ b/validation.md @@ -562,8 +562,8 @@ If you do not want to use the `validate` method on the request, you may create a if ($validator->fails()) { return redirect('/post/create') - ->withErrors($validator) - ->withInput(); + ->withErrors($validator) + ->withInput(); } // Retrieve the validated input...