Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .vitepress/config/sidebar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,8 @@ const sidebar = [
// { text: 'Views', link: '/docs/frontend/mvc' },
{ text: 'Models', link: '/docs/database/models' },
{ text: 'Migrations', link: '/docs/database/migrations' },
{ text: 'Schema', link: '/docs/database/schema' },
{ text: 'JSON Schema', link: '/docs/database/schema' },
// { text: 'Schema Files', link: '/docs/database/files' },
{ text: 'Seeders', link: '/docs/database/seeders' },
{ text: 'Factories', link: '/docs/database/factories' },
{ text: 'Writing Commands', link: '/docs/mvc/commands' },
Expand Down
139 changes: 101 additions & 38 deletions .vitepress/future/files.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
# Database Files
# Schema Files

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.
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.

## What are Database Files?
## What are Schema Files?

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.
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.

```yml [flights.yml]
defaultId: true
increments: true
timestamps: true
columns:
to: string
Expand All @@ -17,23 +17,29 @@ columns:
seeds:
count: 10
data:
to: faker.city
from: faker.city
identifier: faker.uuid
to: 'faker:city'
from: 'faker:city'
identifier: 'faker:uuid'
```

## Creating a Database File
## Creating a Schema File

Aloe comes with a `g:db` command that you can use to generate a database file. You can generate a database file by running:
Aloe comes with a `g:schema` command that you can use to generate a database file. You can generate a database file by running:

```bash:no-line-numbers
php leaf g:db users
php leaf g:schema <table-name>
```

This will create a database file at `app/database/users.yml` which looks like this:
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:

```bash:no-line-numbers
php leaf g:schema users
```

This will create a schema file at `app/database/users.yml` which looks like this:

```yml [users.yml]
defaultId: true
increments: true
timestamps: true
columns:
name: string
Expand All @@ -47,14 +53,14 @@ columns:
seeds:
count: 10
data:
name: faker.name
email: faker.email
password: "{{ bcrypt('password') }}"
name: 'faker:name'
email: 'faker:email'
password: 'hash:password'
```

Breaking down this file, we have:

- `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.
- `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.

- `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.

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

- `seeds`: This is used to set the seeders of the table. The available properties are:
- `count`: This is used to set the number of seeds to generate.
- `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.
- `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. -->
- `truncate`: This is used to truncate the table before seeding.

## DB Migrations
## Database tables

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

```yml [users.yml]
columns:
Expand All @@ -92,27 +98,69 @@ columns:
email_verified_at: timestamp
```

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

```bash:no-line-numbers
php leaf db:migrate
```

<!-- ## DB File Scripts
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:

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.

```yml [users.yml]
```bash:no-line-numbers
php leaf db:migrate users
```

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`:
<!-- ## Database migrations vs data migrations

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.

```php [users.php]
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:

```php [ImportUsersFromOldTable.php]
<?php

use App\Models\User;

class ImportUsersFromOldTable
{
public function up()
{
$oldUsers = getOldUsersAndMapToNewUsers();

foreach ($oldUsers as $oldUser) {
User::create([
'name' => $oldUser->name,
'email' => $oldUser->email,
'password' => $oldUser->password,
'is_from_old_table' => true
]);
}
}

public function down()
{
User::where('is_from_old_table', true)->delete();
}
}
```

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. -->
Now you just need to run the script using the `db:script` command:

```bash:no-line-numbers
php leaf db:script ImportUsersFromOldTable
``` -->

## Migration histories

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.

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.

In the end, this means you can continue to use `php leaf db:rollback` to roll back your database to a previous state.

## DB Seeders
## Seeding your database

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.

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:

Expand All @@ -121,20 +169,23 @@ seeds:
data:
- name: 'Example User'
email: '[email protected]'
password: "{{ bcrypt('password') }}"
password: 'hash:password'
- name: 'Another User'
email: '[email protected]'
password: 'hash:password'
```

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.
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.

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

```yml [users.yml]
```yml{2} [users.yml]
seeds:
count: 10
data:
name: 'Example User'
email: '[email protected]'
password: "{{ bcrypt('password') }}"
password: 'hash:password'
```

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

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.

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

```yml{4,5} [users.yml]
seeds:
count: 10
data:
name: faker.name
email: faker.email
password: "{{ bcrypt('password') }}"
name: 'faker:name'
email: 'faker:email'
password: 'hash:password'
```

In this example, we're generating 10 fake seeds for the `users` table.

After adding your seeds, you can run your seeders using the `db:seed` command:

```bash:no-line-numbers
php leaf db:seed
```

If you want to seed a specific table, you can pass the table name as an argument to the `db:seed` command:

```bash:no-line-numbers
php leaf db:seed users
```
30 changes: 23 additions & 7 deletions src/docs/auth/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,11 @@ The next step is to link your database and start signing users in.

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.

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

```php
::: code-group

```php [Auth connect]
auth()->connect([
'dbtype' => '...',
'charset' => '...',
Expand All @@ -46,16 +48,16 @@ auth()->connect([
]);
```

If you have an existing PDO connection, you can pass it to Leaf Auth:

```php
```php [Existing PDO instance]
$db = new PDO('mysql:dbname=test;host=127.0.0.1', 'root', '');

auth()->dbConnection($db);

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

:::

## Auth + Leaf MVC

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:
Expand Down Expand Up @@ -90,12 +92,26 @@ Leaf Auth doesn't give you any structure for your database, with that, you can s

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:

```php:no-line-numbers
::: code-group

```php:no-line-numbers [Leaf]
auth()->config('id.key', 'admin_id');
```

```php:no-line-numbers [Leaf MVC - config/auth.php]
'id.key' => 'admin_id'
```

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

```php:no-line-numbers
::: code-group

```php:no-line-numbers [Leaf]
auth()->config('db.table', 'admins');
```

```php:no-line-numbers [Leaf MVC - config/auth.php]
'db.table' => 'admins'
```

:::
64 changes: 61 additions & 3 deletions src/docs/auth/login.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,15 +71,25 @@ If you want to use a couple of fields from the user within your application, you

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:

```php:no-line-numbers
::: code-group

```php [Leaf]
auth()->config('session', true);

...

// auth login
```

```php:no-line-numbers [Leaf MVC - config/auth.php]
'session' => true,
```

:::

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:

```php
auth()->config('session', true);

...

// session is automatically started
Expand Down Expand Up @@ -111,6 +121,54 @@ auth()->config('session.cookie', [
]);
```

## Signing in from OAuth

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.

```php
$user = Github()->getResourceOwner($token)->toArray();

$success = auth()->fromOAuth([
'token' => $token,
'user' => [
'name' => $user['name'],
'email' => $user['email'],
'avatar' => $user['avatar_url']
]
]);
```

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.

```php
$success = auth()->fromOAuth([
'token' => $token,
'user' => [
'name' => $user['name'],
'email' => $user['email'],
'avatar' => $user['avatar_url']
]
]);

if (!$success) {
$error = auth()->errors();
}

// user is authenticated
$user = auth()->user();
```

Everything after this point is the same as signing up a user normally.

::: info OAuth Token
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.

```php
$token = auth()->oauthToken();
```

:::

## Auth with no password

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:
Expand Down
Loading