Skip to content

Commit 04564e6

Browse files
authored
Merge pull request #97 from leafsphp/staging
Staging
2 parents 1b5c230 + 4adc120 commit 04564e6

File tree

17 files changed

+502
-147
lines changed

17 files changed

+502
-147
lines changed

.vitepress/config/sidebar.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,8 @@ const sidebar = [
155155
// { text: 'Views', link: '/docs/frontend/mvc' },
156156
{ text: 'Models', link: '/docs/database/models' },
157157
{ text: 'Migrations', link: '/docs/database/migrations' },
158-
{ text: 'Schema', link: '/docs/database/schema' },
158+
{ text: 'JSON Schema', link: '/docs/database/schema' },
159+
// { text: 'Schema Files', link: '/docs/database/files' },
159160
{ text: 'Seeders', link: '/docs/database/seeders' },
160161
{ text: 'Factories', link: '/docs/database/factories' },
161162
{ text: 'Writing Commands', link: '/docs/mvc/commands' },

.vitepress/future/files.md

Lines changed: 101 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
1-
# Database Files
1+
# Schema Files
22

3-
Leaf MVC inherited all the teachings of Laravel and Ruby on Rails, including the use of migrations, seeders, and factories which made creating, testing and seeding databases a breeze. On top of that, Leaf MVC also introduced a new concept called schema files which allowed you to generate migrations from JSON data. While this was a great feature, it was a bit too much for a lot of developers and added to the growing hell of files in your app. To solve this, we've decided to move away from the Rails/Laravel way of doing things and introduce a new way of handling database files in Leaf MVC.
3+
Leaf MVC inherited all the teachings of Laravel and Ruby on Rails, including the use of migrations, seeders, and factories which made creating, testing and seeding databases a breeze. It even introduced schema files, allowing you to generate migrations from JSON data. While helpful, this added complexity and clutter to projects. To simplify things, we’re moving away from the Rails/Laravel approach and creating a more streamlined, Leaf-like solution.
44

5-
## What are Database Files?
5+
## What are Schema Files?
66

7-
Database files are a way to handle migrations, seeders, and factories in a single file. This way, you can easily manage your database structure without having to create multiple files for each operation and without having to repeat yourself all over your app. Database files are written in yaml which makes them incredibly easy to read and write.
7+
Schema files build on the JSON schema idea we introduced in earlier Leaf MVC versions, but they take things further. Instead of juggling separate files for migrations, seeders, and factories, you can handle everything in one place. They’re written in YAML, so they’re easy to read and work with—no extra hassle, no repeating yourself.
88

99
```yml [flights.yml]
10-
defaultId: true
10+
increments: true
1111
timestamps: true
1212
columns:
1313
to: string
@@ -17,23 +17,29 @@ columns:
1717
seeds:
1818
count: 10
1919
data:
20-
to: faker.city
21-
from: faker.city
22-
identifier: faker.uuid
20+
to: 'faker:city'
21+
from: 'faker:city'
22+
identifier: 'faker:uuid'
2323
```
2424
25-
## Creating a Database File
25+
## Creating a Schema File
2626
27-
Aloe comes with a `g:db` command that you can use to generate a database file. You can generate a database file by running:
27+
Aloe comes with a `g:schema` command that you can use to generate a database file. You can generate a database file by running:
2828

2929
```bash:no-line-numbers
30-
php leaf g:db users
30+
php leaf g:schema <table-name>
3131
```
3232

33-
This will create a database file at `app/database/users.yml` which looks like this:
33+
Remember, every schema file is tied to a table in your database. When you run the command above, Leaf will create a schema file in your `app/database` directory with the name `<table-name>.yml`. Here’s an example:
34+
35+
```bash:no-line-numbers
36+
php leaf g:schema users
37+
```
38+
39+
This will create a schema file at `app/database/users.yml` which looks like this:
3440

3541
```yml [users.yml]
36-
defaultId: true
42+
increments: true
3743
timestamps: true
3844
columns:
3945
name: string
@@ -47,14 +53,14 @@ columns:
4753
seeds:
4854
count: 10
4955
data:
50-
name: faker.name
51-
email: faker.email
52-
password: "{{ bcrypt('password') }}"
56+
name: 'faker:name'
57+
email: 'faker:email'
58+
password: 'hash:password'
5359
```
5460

5561
Breaking down this file, we have:
5662

57-
- `defaultId`: This is used to set the default id of the table. If set to `true`, the table will have an auto-incrementing id. If set to `false`, the table will not have an id.
63+
- `increments`: This is used to set the default id of the table. If set to `true`, the table will have an auto-incrementing id. If set to `false`, the table will not have an id, and you can set your own primary key.
5864

5965
- `timestamps`: This is used to set timestamps on the table. If set to `true`, the table will have `created_at` and `updated_at` columns. If set to `false`, the table will not have timestamps.
6066

@@ -74,12 +80,12 @@ Breaking down this file, we have:
7480

7581
- `seeds`: This is used to set the seeders of the table. The available properties are:
7682
- `count`: This is used to set the number of seeds to generate.
77-
- `data`: This is used to set the data of the seeds. The key is the column name and the value is the value of the column. You can use `faker.[value]` to generate fake data for the column. You can also use `{{ [value] }}` to use PHP code.
83+
- `data`: This is used to set the data of the seeds. The key is the column name and the value is the value of the column. You can use `faker:[value]` to generate fake data for the column. <!-- You can also use `{{ [value] }}` to use PHP code, but this is a separate PHP thread which means you can't use variables from the current scope. -->
7884
- `truncate`: This is used to truncate the table before seeding.
7985

80-
## DB Migrations
86+
## Database tables
8187

82-
Traditionally, migrations are used to create database tables and modify them. In Leaf MVC, you can create migrations in your database files. The `columns` key in your database file is used to create migrations. Here's an example of a migration:
88+
Traditionally, migrations are used to create database tables and modify them. In Leaf MVC, every schema file is tied to a particular table which is the name of the file. All you need to do is modify the columns of the table using the `columns` key in your schema file. Here's an example:
8389

8490
```yml [users.yml]
8591
columns:
@@ -92,27 +98,69 @@ columns:
9298
email_verified_at: timestamp
9399
```
94100

95-
In this example, we create a migration that creates a `users` table with `name`, `email`, `password`, and `email_verified_at` columns. To run your migrations, you can use the `db:migrate` command:
101+
In this example, we create a `users` table with `name`, `email`, `password`, and `email_verified_at` columns. We can then migrate this table to our database using the `db:migrate` command:
96102

97103
```bash:no-line-numbers
98104
php leaf db:migrate
99105
```
100106

101-
<!-- ## DB File Scripts
107+
You can have multiple schema files in your `app/database` directory, each tied to a particular table. When you run the `db:migrate` command, Leaf will migrate all the tables in your `app/database` directory. If you want to migrate only a specific table, you can pass the table name as an argument to the `db:migrate` command:
102108

103-
We understand that you might have some complicated functionality that you would want to run when migrating your database, which is why we allow you to run PHP scripts in your database files. This way, you can run any PHP code you want when migrating your database.
104-
105-
```yml [users.yml]
109+
```bash:no-line-numbers
110+
php leaf db:migrate users
106111
```
107112

108-
Now you need to create the PHP script that will run when migrating your database. You can create a PHP script at `app/database/scripts/users.php`:
113+
<!-- ## Database migrations vs data migrations
114+
115+
Usually, when making substancial changes to your database, you would create a migration file which is usually in charge of modifying the structure of your database. In some situations, you might want to run some kind of data migration which may copy data from one table to another, or run some kind of data manipulation on your recently migrated database. Some frameworks combine these two into one, but in Leaf MVC, we separate these two because we believe they are two different things. While database migrations are common, data migrations are not so common and are usually done manually.
109116

110-
```php [users.php]
117+
Leaf MVC provides database scripts which you can use to handle your data migrations. Separating database migrations from data migrations allows you to safely roll-back your data migrations without affecting your database structure. Here's an example of a database script:
118+
119+
```php [ImportUsersFromOldTable.php]
120+
<?php
121+
122+
use App\Models\User;
123+
124+
class ImportUsersFromOldTable
125+
{
126+
public function up()
127+
{
128+
$oldUsers = getOldUsersAndMapToNewUsers();
129+
130+
foreach ($oldUsers as $oldUser) {
131+
User::create([
132+
'name' => $oldUser->name,
133+
'email' => $oldUser->email,
134+
'password' => $oldUser->password,
135+
'is_from_old_table' => true
136+
]);
137+
}
138+
}
139+
140+
public function down()
141+
{
142+
User::where('is_from_old_table', true)->delete();
143+
}
144+
}
111145
```
112146

113-
In this example, we're running a PHP script that creates a new table in the database, but checks if particular columns exist before creating the table. -->
147+
Now you just need to run the script using the `db:script` command:
148+
149+
```bash:no-line-numbers
150+
php leaf db:script ImportUsersFromOldTable
151+
``` -->
152+
153+
## Migration histories
154+
155+
Migration histories are used to keep track of the migrations that have been run on your database. This is useful for keeping track of the state of your database so you can easily roll back to a previous state if needed. Unlike in other frameworks, Leaf MVC does require you to manually create migrations to keep track of your migration history. This is done automatically for you.
156+
157+
Every time you edit a schema file and run the `db:migrate` command, Leaf will automatically keep track of the migrations that have been run on your database, which means less time scrambling through migration files and more time building your app.
158+
159+
In the end, this means you can continue to use `php leaf db:rollback` to roll back your database to a previous state.
114160

115-
## DB Seeders
161+
## Seeding your database
162+
163+
Database seeds are a way to populate a database with initial data. This initial data can be used to set up default values or pre-populate a database with test data. Database seeds typically contain small amounts of data, such as default settings, test data, or sample records.
116164

117165
Seeders are used to populate your database with dummy data. In Leaf MVC, you can create seeders in your database files. The `seeders` key in your database file is used to create seeders. Here's an example of a seeder:
118166

@@ -121,20 +169,23 @@ seeds:
121169
data:
122170
- name: 'Example User'
123171
124-
password: "{{ bcrypt('password') }}"
172+
password: 'hash:password'
173+
- name: 'Another User'
174+
175+
password: 'hash:password'
125176
```
126177

127-
In this example, we create a seeder that seeds the `users` table with an example user. We are passing an array of seeds to the `data` key, each seed being a key value pair of column name and value.
178+
In this example, we create a seeder that seeds the `users` table with two example users. We are passing an array of seeds to the `data` key, each seed being a key value pair of column name and value.
128179

129-
If you want to generate multiple seeds, you can pass an object to the `data` key instead of an array together with a `count` key:
180+
Another way to generate multiple seeds is to use the `count` key. When using the `count` key, you can pass an integer value to generate multiple seeds with the same data. Here's an example:
130181

131-
```yml [users.yml]
182+
```yml{2} [users.yml]
132183
seeds:
133184
count: 10
134185
data:
135186
name: 'Example User'
136187
137-
password: "{{ bcrypt('password') }}"
188+
password: 'hash:password'
138189
```
139190

140191
After creating your seeder, you can run your seeders using the `db:seed` command:
@@ -145,15 +196,27 @@ php leaf db:seed
145196

146197
This will generate 10 seeds for the `users` table with the same data which is not very useful. To generate multiple fake seeds, you can use what other frameworks call a factory.
147198

148-
In Leaf MVC, factories and seeders are the same thing as we believe this confusion is unnecessary. If you want to generate fake data for your seeders, you can add `faker.[value]` as the value of a column in your seeder. Here's an example:
199+
In Leaf MVC, factories and seeders are the same thing as we believe this confusion is unnecessary. If you want to generate fake data for your seeders, you can add `faker:[value]` as the value of a column in your seeder. Here's an example:
149200

150201
```yml{4,5} [users.yml]
151202
seeds:
152203
count: 10
153204
data:
154-
name: faker.name
155-
email: faker.email
156-
password: "{{ bcrypt('password') }}"
205+
name: 'faker:name'
206+
email: 'faker:email'
207+
password: 'hash:password'
157208
```
158209

159210
In this example, we're generating 10 fake seeds for the `users` table.
211+
212+
After adding your seeds, you can run your seeders using the `db:seed` command:
213+
214+
```bash:no-line-numbers
215+
php leaf db:seed
216+
```
217+
218+
If you want to seed a specific table, you can pass the table name as an argument to the `db:seed` command:
219+
220+
```bash:no-line-numbers
221+
php leaf db:seed users
222+
```

src/docs/auth/index.md

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,11 @@ The next step is to link your database and start signing users in.
3232

3333
To do any kind of authentication, you need to connect to some kind of database which will store your users' data. If you are already using Leaf DB or Leaf MVC, then your database connection will automatically be used by Leaf Auth, so you don't need to connect to your database again.
3434

35-
If you are not using Leaf DB or Leaf MVC, you can connect to your database manually:
35+
If you are **NOT** using Leaf DB or Leaf MVC, you can connect to your database manually:
3636

37-
```php
37+
::: code-group
38+
39+
```php [Auth connect]
3840
auth()->connect([
3941
'dbtype' => '...',
4042
'charset' => '...',
@@ -46,16 +48,16 @@ auth()->connect([
4648
]);
4749
```
4850

49-
If you have an existing PDO connection, you can pass it to Leaf Auth:
50-
51-
```php
51+
```php [Existing PDO instance]
5252
$db = new PDO('mysql:dbname=test;host=127.0.0.1', 'root', '');
5353

5454
auth()->dbConnection($db);
5555

5656
// you can use leaf auth the same way you always have
5757
```
5858

59+
:::
60+
5961
## Auth + Leaf MVC
6062

6163
If you are using Leaf MVC, you can set up Leaf Auth to work with your default database connection by heading over to the `public/index.php` file and uncommenting the line that connects to the database:
@@ -90,12 +92,26 @@ Leaf Auth doesn't give you any structure for your database, with that, you can s
9092

9193
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:
9294

93-
```php:no-line-numbers
95+
::: code-group
96+
97+
```php:no-line-numbers [Leaf]
9498
auth()->config('id.key', 'admin_id');
9599
```
96100
101+
```php:no-line-numbers [Leaf MVC - config/auth.php]
102+
'id.key' => 'admin_id'
103+
```
104+
97105
2. Leaf Auth assumes that you will save your users in a database table named `users`, this might however not be the case for your application. If you want to use a different table, you can configure Leaf Auth using `db.table`:
98106
99-
```php:no-line-numbers
107+
::: code-group
108+
109+
```php:no-line-numbers [Leaf]
100110
auth()->config('db.table', 'admins');
101111
```
112+
113+
```php:no-line-numbers [Leaf MVC - config/auth.php]
114+
'db.table' => 'admins'
115+
```
116+
117+
:::

src/docs/auth/login.md

Lines changed: 61 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -71,15 +71,25 @@ If you want to use a couple of fields from the user within your application, you
7171

7272
Leaf uses token based authentication by default which uses a JWT to authenticate your users. Sessions are a more common way to authenticate users in fullstack applications. To switch to session based authentication, you can update your auth config:
7373

74-
```php:no-line-numbers
74+
::: code-group
75+
76+
```php [Leaf]
7577
auth()->config('session', true);
78+
79+
...
80+
81+
// auth login
82+
```
83+
84+
```php:no-line-numbers [Leaf MVC - config/auth.php]
85+
'session' => true,
7686
```
7787

88+
:::
89+
7890
With the addition of session auth, `login()` will automatically start a session, but will behave in the same way, which means redirects and any other functionality you need will be left up to you to handle:
7991

8092
```php
81-
auth()->config('session', true);
82-
8393
...
8494

8595
// session is automatically started
@@ -111,6 +121,54 @@ auth()->config('session.cookie', [
111121
]);
112122
```
113123

124+
## Signing in from OAuth
125+
126+
Some applications only allow users to sign in using OAuth which means there's no need for users to add emails or passwords. Leaf Auth provides the `fromOAuth()` function which allows you to create a session or token for a user without needing a password.
127+
128+
```php
129+
$user = Github()->getResourceOwner($token)->toArray();
130+
131+
$success = auth()->fromOAuth([
132+
'token' => $token,
133+
'user' => [
134+
'name' => $user['name'],
135+
'email' => $user['email'],
136+
'avatar' => $user['avatar_url']
137+
]
138+
]);
139+
```
140+
141+
If the user is successfully saved in the database, a session or token is created for them and the rest of the process is the same as signing up a user normally. If Leaf Auth fails to save the user, the method returns `false`. You can then use the `errors()` method to get the error message.
142+
143+
```php
144+
$success = auth()->fromOAuth([
145+
'token' => $token,
146+
'user' => [
147+
'name' => $user['name'],
148+
'email' => $user['email'],
149+
'avatar' => $user['avatar_url']
150+
]
151+
]);
152+
153+
if (!$success) {
154+
$error = auth()->errors();
155+
}
156+
157+
// user is authenticated
158+
$user = auth()->user();
159+
```
160+
161+
Everything after this point is the same as signing up a user normally.
162+
163+
::: info OAuth Token
164+
The `fromOAuth()` method expects an OAuth token to be passed in. This token is usually gotten from the OAuth provider you are using. You can later use this token to make requests to the OAuth provider on behalf of the user. Leaf Auth saves this token so you can retrieve it later using the `auth()->oauthToken()` method.
165+
166+
```php
167+
$token = auth()->oauthToken();
168+
```
169+
170+
:::
171+
114172
## Auth with no password
115173

116174
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:

0 commit comments

Comments
 (0)