Skip to content

Commit 2a08e43

Browse files
committed
feat: update auth & db docs
1 parent 45162d8 commit 2a08e43

File tree

11 files changed

+136
-63
lines changed

11 files changed

+136
-63
lines changed

.vitepress/config/sidebar.ts

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -46,16 +46,6 @@ const sidebar = [
4646
{ text: 'CORS', link: '/docs/http/cors' },
4747
],
4848
},
49-
{
50-
text: 'Sessions',
51-
// collapsible: true,
52-
// collapsed: true,
53-
items: [
54-
{ text: 'Using Sessions', link: '/docs/http/session' },
55-
{ text: 'Session Flash', link: '/docs/http/flash' },
56-
{ text: 'Cookies', link: '/docs/http/cookies' },
57-
],
58-
},
5949
{
6050
text: 'Config & Deployment',
6151
// collapsible: true,
@@ -106,6 +96,16 @@ const sidebar = [
10696
{ text: 'Build your own auth library', link: '/docs/auth/helpers' },
10797
],
10898
},
99+
{
100+
text: 'Sessions',
101+
// collapsible: true,
102+
// collapsed: true,
103+
items: [
104+
{ text: 'Using Sessions', link: '/docs/http/session' },
105+
{ text: 'Session Flash', link: '/docs/http/flash' },
106+
{ text: 'Cookies', link: '/docs/http/cookies' },
107+
],
108+
},
109109
{
110110
text: 'Security',
111111
// collapsible: true,

.vitepress/theme/styles/index.css

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@
3636
}
3737

3838
html.dark {
39-
--vp-c-banner: var(--vp-c-bg-soft);
39+
--vp-c-banner: #0e5f3c;
4040
--vp-code-color: #3eaf7c;
4141
--vp-c-bg: #001e26;
4242
--vp-c-bg-alt: #001318;

src/docs/auth/index.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ That's all you need to do. Leaf Auth will automatically connect to your database
8484

8585
Leaf Auth doesn't give you any structure for your database, with that, you can structure your database in any way you prefer. However, there are some things you should note:
8686

87-
1. By default, Leaf Auth assumes that your database primary key is `id`. If you have a database where you are using another field, say `admin_id` as the primary key, you will need to tell Leaf the name of your primary key. You can do this using the `ID_KEY` config:
87+
1. By default, Leaf Auth assumes that your database primary key is `id`. If you have a database where you are using another field, say `admin_id` as the primary key, you will need to tell Leaf the name of your primary key. You can do this using the `id.key` config:
8888

8989
```php:no-line-numbers
9090
auth()->config('id.key', 'admin_id');

src/docs/auth/login.md

Lines changed: 32 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ $data = auth()->login([
5050
'password' => 'password'
5151
]);
5252

53-
if($data) {
53+
if ($data) {
5454
// User is authenticated
5555
$token = $data->token;
5656
$user = $data->user;
@@ -70,13 +70,33 @@ Leaf uses token based authentication by default which uses a JWT to authenticate
7070
auth()->config('session', true);
7171
```
7272

73-
With this, a new login will create a session for the user. If your app requires users to be redirected to a different page after login, you can configure Leaf Auth to do just that:
73+
With the addition of session auth, `login()` will automatically start a session, but will leave redirects and every other thing to you:
7474

75-
```php:no-line-numbers
76-
auth()->config('session.loginRedirect', '/dashboard');
75+
```php
76+
auth()->config('session', true);
77+
78+
...
79+
80+
// session is automatically started
81+
$data = auth()->login([
82+
'email' => '[email protected]',
83+
'password' => 'password'
84+
]);
85+
86+
if ($data) {
87+
// User is authenticated
88+
$user = $data->user;
89+
90+
response()->redirect('/dashboard');
91+
} else {
92+
// User is not authenticated
93+
$error = auth()->errors();
94+
}
7795
```
7896

79-
You can also control things like the cookie settings and more:
97+
This lets you handle complex control flows...or the simple redirect ones in a manner you prefer.
98+
99+
If you need finer control over how PHP creates your session, you can add your own config to the `session.cookie` config:
80100

81101
```php
82102
auth()->config('session.cookie', [
@@ -86,12 +106,6 @@ auth()->config('session.cookie', [
86106
]);
87107
```
88108

89-
You can also generate JWT tokens for your sessions if you want to:
90-
91-
```php:no-line-numbers
92-
auth()->config('session.jwt', true);
93-
```
94-
95109
## Auth with no password
96110

97111
Leaf Auth usually expects a password field to authenticate users. This is necessary because most applications require a password to authenticate users. The field is usually named `password`, however, you can configure Leaf Auth to expect a different field:
@@ -220,7 +234,7 @@ $data = auth()->update([
220234
'email' => '[email protected]'
221235
]);
222236

223-
if(!$data) {
237+
if (!$data) {
224238
$error = auth()->errors();
225239
// ['email' => 'The email already exists']
226240
}
@@ -235,12 +249,17 @@ auth()->logout();
235249

236250
// or redirect the user after logout
237251
auth()->logout('/login');
252+
253+
// or redirect to a named route
254+
auth()->logout(['homepage']);
238255
```
239256

240-
By default, the logout method will just end the user's session. If you want to perform a custom operation when a user logs out, you can set a handler for the logout operation:
257+
If you want to perform a custom operation when a user logs out, you can set a handler for the logout operation:
241258

242259
```php
243260
auth()->config('session.logout', function () {
244261
// your logout handler
245262
});
246263
```
264+
265+
This will ignore whatever route is passed into the `logout()` method and rely solely on the function passed into the session.logout config.

src/docs/auth/protected-routes.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,8 @@ app()->get('/protected', function () {
4747
} else {
4848
// user is not logged in
4949
response()->json([
50-
"error" => "Unauthorized",
51-
"data" => auth()->errors(),
50+
'error' => 'Unauthorized',
51+
'data' => auth()->errors(),
5252
], 401);
5353
}
5454
});

src/docs/auth/signup.md

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ $data = auth()->register([
8080
'password' => 'password'
8181
]);
8282

83-
if($data) {
83+
if ($data) {
8484
// User is authenticated
8585
$token = $data->token;
8686
$user = $data->user;
@@ -107,7 +107,7 @@ $data = auth()->register([
107107
'password' => 'password'
108108
]);
109109

110-
if(!$data) {
110+
if (!$data) {
111111
$error = auth()->errors();
112112
// ['email' => 'The email already exists']
113113
}
@@ -158,16 +158,26 @@ Leaf uses token based authentication by default which uses a JWT to authenticate
158158
auth()->config('session', true);
159159
```
160160

161-
This however won't automatically log in a user after registration meaning no session will be created after a user signs up. If you want to automatically log in a user after registration, you can configure Leaf Auth to do that:
161+
Switching to session auth does not change the default behaviour of the `register()` method. It won't create a session or do anything fancy by default. If you want to create a session immediately after signing a user up, you can pass true to the `session.register` config:
162162

163163
```php:no-line-numbers
164164
auth()->config('session.register', true);
165-
```
166165
167-
You can also set the URL where your app should redirect users to after registration:
166+
...
168167
169-
```php:no-line-numbers
170-
auth()->config('session.registerRedirect', '/dashboard');
168+
// will create a session
169+
$data = auth()->register([
170+
'username' => 'example',
171+
'email' => '[email protected]',
172+
'password' => 'password'
173+
]);
174+
175+
if ($data) {
176+
response()->redirect('/dashboard');
177+
} else {
178+
$error = auth()->errors();
179+
// ['email' => 'The email already exists']
180+
}
171181
```
172182

173183
You can also control things like the cookie settings and more:
@@ -179,9 +189,3 @@ auth()->config('session.cookie', [
179189
'samesite' => 'lax'
180190
]);
181191
```
182-
183-
You can also generate JWT tokens for your sessions if you want to:
184-
185-
```php:no-line-numbers
186-
auth()->config('session.jwt', true);
187-
```

src/docs/database/builder.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,41 @@ db()
224224

225225
This will delete the row in the users table with the `id` of 1.
226226

227+
## Database Transactions
228+
229+
Database transactions are a way to ...
230+
Leaf DB allows you to create database transactions using the `transaction()` method. It takes in a callable which is every query you want to perform as part of your transaction.
231+
232+
```php
233+
db()->transaction(function ($db) {
234+
$db->insert('purchases')->params(...)->execute();
235+
$db->update('balances')->params(...)->where(...)->execute();
236+
237+
// you can even do external stuff here
238+
$res = fetch()->post(...)
239+
240+
$doSomething = $res->data;
241+
242+
...
243+
});
244+
```
245+
246+
If anything in the function fails, Leaf will automatically rollback every change that has been made in the database till that point and return `false`. You can get the associated error using the `errors()` method.
247+
248+
```php
249+
$success = db()->transaction(function () {
250+
...
251+
});
252+
253+
if ($success) {
254+
// do something
255+
} else {
256+
$errors = db()->errors();
257+
}
258+
```
259+
260+
This is useful especially when you have a set of queries that rely on third party influence.
261+
227262
## Hiding columns from results
228263

229264
Sometimes you might want to hide certain columns from the results of a query. For instance, you might want to hide the password column from the results of a query on the users table. Leaf DB provides a `hide()` method that allows you to do this.

src/docs/http/caching.md

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -32,10 +32,10 @@ An ETag is a unique identifier for a resource URI. After setting the Etag header
3232
Setting an ETag with Leaf is very simple. Invoke Leaf’s etag method in your route callback, passing it a unique ID as the first and only argument.
3333

3434
```php
35-
use \Leaf\Http\Headers;
35+
use Leaf\Http\Cache;
3636

3737
app()->get('/', function () {
38-
Headers::etag('unique-tag');
38+
Cache::etag('unique-tag');
3939

4040
echo 'This will be cached after the initial request!';
4141
});
@@ -50,11 +50,11 @@ Used in conjunction with the Leaf application’s etag or lastModified methods,
5050
The expires method accepts one argument: an integer UNIX timestamp, or a string to be parsed with `strtotime()`.
5151

5252
```php
53-
use \Leaf\Http\Headers;
53+
use Leaf\Http\Cache;
5454

5555
app()->get('/', function () {
56-
Headers::etag('unique-tag');
57-
Headers::expires('+1 week');
56+
Cache::etag('unique-tag');
57+
Cache::expires('+1 week');
5858

5959
echo 'This will be cached client-side for one week';
6060
});
@@ -67,10 +67,10 @@ A Leaf provides built-in support for HTTP caching using the resource’s last mo
6767
Setting a last modified date with Leaf is very simple. You only need to invoke the Leaf’s lastModified() method in your route callback passing in a UNIX timestamp of the last modification date for the given resource. Be sure the lastModified() method’s timestamp updates along with the resource’s last modification date; otherwise, the browser client will continue serving its outdated cache.
6868

6969
```php
70-
use \Leaf\Http\Headers;
70+
use Leaf\Http\Cache;
7171

7272
app()->get('/', function () {
73-
Headers::lastModified(1617383991);
73+
Cache::lastModified(1617383991);
7474

7575
echo 'This will be cached after the initial request!';
7676
});
@@ -81,7 +81,7 @@ app()->get('/', function () {
8181
There are other cache-related headers that Leaf doesn't provide direct methods for. You can set these headers directly using Leaf's Headers::set() method.
8282

8383
```php
84-
use \Leaf\Http\Headers;
84+
use Leaf\Http\Headers;
8585

8686
app()->get('/', function () {
8787
Headers::set('Cache-Control', 'public, max-age=3600');

src/docs/utils/fetch.md

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -77,38 +77,48 @@ It gets even simpler when you're making a GET or POST request. Fetch provides so
7777
GET requests are the most common type of request you'll make when fetching data from an API. Fetch makes it easy to make GET requests using the global `fetch()` function. Here's an example of how you can make a GET request using Fetch:
7878

7979
```php
80-
$res = fetch("https://jsonplaceholder.typicode.com/todos/");
80+
$res = fetch()->get('https://jsonplaceholder.typicode.com/todos/');
8181

8282
// data returned is saved in the $data property just like axios
8383
response()->json($res->data);
8484
```
8585

86-
Every request made using Fetch returns a `FetchResponse` object. This object contains the response data, status code, headers, and more. You can access the response data using the `data` property.
86+
Or you pass the url directly to the `fetch()` function.
8787

88-
## Making POST Requests
88+
```php
89+
$res = fetch('https://jsonplaceholder.typicode.com/todos/');
90+
91+
// data returned is saved in the $data property just like axios
92+
response()->json($res->data);
93+
```
8994

90-
POST requests are used to send data to a server to create or update a resource. You can make POST requests using Fetch by passing an array of data as the second argument to the `fetch()` function. Here's an example:
95+
## Making Other Requests
96+
97+
Fetch works just like the Leaf router, in a sense that every request type has a shortcut method. You can call `get()`, `post()`, `put()`, `patch()`, `delete()` and `options()` to make any kind of request you want.
9198

9299
```php
93-
$res = fetch("https://jsonplaceholder.typicode.com/posts", [
94-
"title" => "foo",
95-
"body" => "bar",
96-
"userId" => 1
100+
$res = fetch()->post('https://jsonplaceholder.typicode.com/posts', [
101+
'title' => 'foo',
102+
'body' => 'bar',
103+
'userId' => 1
97104
]);
98105

106+
fetch()->put(...);
107+
fetch()->patch(...);
108+
fetch()->delete(...);
109+
fetch()->options(...);
110+
99111
response()->json($res->data);
100112
```
101113

102-
Once `fetch()` detects that you're passing an array as the second argument, it automatically converts the request to a POST request.
103-
104114
## Setting Base URLs
105115

106116
Base URLs are useful when you're making requests to the same server or API. One popular use case for base URLs is when you're working with a REST API as it allows you to ignore typing lengthy URLs for every request.
107117

108-
You can set a base URL for all your requests using the `baseUrl()` method on the `Fetch` class.
118+
You can set a base URL for all your requests using the `baseUrl()` method on the `fetch` function.
109119

110120
```php
111-
Leaf\Fetch::baseUrl('https://jsonplaceholder.typicode.com');
121+
fetch()->baseUrl('https://jsonplaceholder.typicode.com');
112122
```
113123

114124
Now you can make requests without specifying the full URL.
@@ -118,7 +128,7 @@ Now you can make requests without specifying the full URL.
118128
$response = fetch('/todos');
119129

120130
// https://jsonplaceholder.typicode.com/posts
121-
$response = fetch('/posts', [
131+
$response = fetch()->post('/posts', [
122132
'title' => 'foo',
123133
'body' => 'bar',
124134
'userId' => 1,

src/public/sponsors.json

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -393,6 +393,11 @@
393393
"url": "https://github.com/1mahdimf",
394394
"img": "https://avatars.githubusercontent.com/u/8771082?v=4"
395395
},
396+
{
397+
"name": "Isaac",
398+
"url": "https://github.com/isaac-araujo",
399+
"img": "https://avatars.githubusercontent.com/u/84479744?v=4"
400+
},
396401
{
397402
"name": "pakuningratan",
398403
"url": "https://github.com/pakuningratan",

0 commit comments

Comments
 (0)