From 33a453a3f51a27c37b5ab15dc061df63973c673f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gu=CC=88nther=20Debrauwer?= Date: Tue, 16 Apr 2024 19:53:51 +0200 Subject: [PATCH 1/2] Document afterQuery method --- eloquent.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/eloquent.md b/eloquent.md index 0a5cd0d4135..7aeb0631378 100644 --- a/eloquent.md +++ b/eloquent.md @@ -32,6 +32,7 @@ - [Query Scopes](#query-scopes) - [Global Scopes](#global-scopes) - [Local Scopes](#local-scopes) +- [After Query Hook](#after-query-hook) - [Comparing Models](#comparing-models) - [Events](#events) - [Using Closures](#events-using-closures) @@ -1373,6 +1374,17 @@ Once the expected arguments have been added to your scope method's signature, yo $users = User::ofType('admin')->get(); + +## After Query Hook + +If you want to alter models you queried from the database, you probably would do that on the result returned by the Eloquent query. The code that makes those alterations lives outside your Eloquent query code in that case. If you want to keep code within your query code, you can use the `afterQuery` method. The provided closure always receives a collection of models as its first parameter. You can make changes to those models or even remove models you don't need. + + User::query() + ->afterQuery(function (Collection $users) { + // Alter users ... + }) + ->get(); + ## Comparing Models From c844a3cf9a9d4b57f8ff472a246adc7a9a320f19 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gu=CC=88nther=20Debrauwer?= Date: Tue, 16 Apr 2024 19:55:31 +0200 Subject: [PATCH 2/2] Fix typo --- eloquent.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/eloquent.md b/eloquent.md index 7aeb0631378..a898963533d 100644 --- a/eloquent.md +++ b/eloquent.md @@ -1377,7 +1377,7 @@ Once the expected arguments have been added to your scope method's signature, yo ## After Query Hook -If you want to alter models you queried from the database, you probably would do that on the result returned by the Eloquent query. The code that makes those alterations lives outside your Eloquent query code in that case. If you want to keep code within your query code, you can use the `afterQuery` method. The provided closure always receives a collection of models as its first parameter. You can make changes to those models or even remove models you don't need. +If you want to alter models you queried from the database, you probably would do that on the result returned by the Eloquent query. The code that makes those alterations lives outside your Eloquent query code in that case. If you want to keep that code within your query code, you can use the `afterQuery` method. The provided closure always receives a collection of models as its first parameter. You can make changes to those models or even remove models you don't need. User::query() ->afterQuery(function (Collection $users) {