Skip to content

Commit 3185352

Browse files
authored
Merge pull request #1 from nullthoughts/dev
Code cleanup & documentation
2 parents 673b8a2 + 5df01e3 commit 3185352

File tree

3 files changed

+52
-2
lines changed

3 files changed

+52
-2
lines changed

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,5 @@
99
Homestead.json
1010
Homestead.yaml
1111
npm-debug.log
12-
yarn-error.log
12+
yarn-error.log
13+
SCRATCH.md

README.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# Laravel Latest Relation
2+
Eloquent macros for querying the latest HasMany relationship in Laravel
3+
4+
## Installation
5+
Install via composer:
6+
`composer require nullthoughts/laravel-latest-relation`
7+
8+
## Usage / Examples
9+
Use the Builder methods inside a whereHas closure:
10+
11+
### whereLatest($column, $value)
12+
**Query**
13+
```php
14+
$users = User::whereHas('logins', function ($query) {
15+
$query->whereLatest('device_type', 'desktop');
16+
});
17+
```
18+
19+
**Dynamic Scope**
20+
```php
21+
public function scopeByCondition($query, $condition)
22+
{
23+
return $query->whereHas('logins', function ($query) use ($device) {
24+
$query->whereLatest('device_type', $device);
25+
});
26+
}
27+
```
28+
29+
### latestRelation()
30+
**Query**
31+
```php
32+
$users = User::whereHas('logins', function ($query) {
33+
$query->latestRelation()->whereBetween(
34+
'created_at', [
35+
Carbon::now()->startOfDay(),
36+
Carbon::now()->endOfDay()
37+
]);
38+
});
39+
```
40+
41+
**Dynamic Scope**
42+
```php
43+
public function scopeByCondition($query, $condition)
44+
{
45+
return $query->whereHas('logins', function ($query) {
46+
$query->latestRelation()->whereNotNull('device_type');
47+
});
48+
}
49+
```

src/ServiceProvider.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ public function boot()
1818
return $this->where('id', function ($sub) use ($where) {
1919
$sub->from($this->from)
2020
->selectRaw('max(id)')
21-
->whereRaw($where['first'] . ' = ' . $where['second']);
21+
->whereColumn($where['first'], $where['second']);
2222
});
2323
});
2424

0 commit comments

Comments
 (0)