Skip to content

Commit b1f3314

Browse files
authored
Merge pull request #30 from tonysm/turbo-native-request-macro
Adds the wasFromTurboNative request macro
2 parents e83d033 + 22f6b4b commit b1f3314

File tree

3 files changed

+25
-2
lines changed

3 files changed

+25
-2
lines changed

README.md

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -697,13 +697,21 @@ Alternatively, you can check if it's not a Turbo Native visit using the `@unless
697697
@endunlessturbonative
698698
```
699699

700-
You may also check if the request was made from a Turbo Native visit using the TurboFacade, like so:
700+
You may also check if the request was made from a Turbo Native visit using the request macro:
701+
702+
```php
703+
if (request()->wasFromTurboNative()) {
704+
// ...
705+
}
706+
```
707+
708+
Or the Turbo Facade directly, like so:
701709

702710
```php
703711
use Tonysm\TurboLaravel\Facades\Turbo;
704712

705713
if (Turbo::isTurboNativeVisit()) {
706-
// Do something for mobile specific requests.
714+
// ...
707715
}
708716
```
709717

src/TurboServiceProvider.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,10 @@ private function bindRequestAndResponseMacros(): void
9797
Request::macro('wantsTurboStream', function () {
9898
return Str::contains($this->header('Accept'), Turbo::TURBO_STREAM_FORMAT);
9999
});
100+
101+
Request::macro('wasFromTurboNative', function () {
102+
return TurboFacade::isTurboNativeVisit();
103+
});
100104
}
101105

102106
protected function bindTestResponseMacros()

tests/Http/RequestMacrosTest.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace Tonysm\TurboLaravel\Tests\Http;
44

55
use Illuminate\Http\Request;
6+
use Tonysm\TurboLaravel\Facades\Turbo as TurboFacade;
67
use Tonysm\TurboLaravel\Tests\TestCase;
78
use Tonysm\TurboLaravel\Turbo;
89

@@ -20,4 +21,14 @@ public function wants_turbo_stream()
2021
]);
2122
$this->assertTrue($request->wantsTurboStream(), 'Expected request to want a turbo stream response, but it did not.');
2223
}
24+
25+
/** @test */
26+
public function was_from_turbo_native()
27+
{
28+
$request = Request::create('/hello');
29+
$this->assertFalse($request->wasFromTurboNative());
30+
31+
TurboFacade::setVisitingFromTurboNative();
32+
$this->assertTrue($request->wasFromTurboNative());
33+
}
2334
}

0 commit comments

Comments
 (0)