Tutorial: Adding Fields to Users/Characters/Etc
Contents
INCOMPLETE TUTORIAL!
One of the best parts about Lorekeeper is how customizable it is. Beyond Extensions, you can go in and add entire new columns to the database to store new information that's custom to your site or to the extension you might be working on.
This tutorial will cover the basics of adding new fields to Users, though you can implement the same logic in adding fields to items, characters, etc.
The Parts of the Process
Before you get into the code, you should understand the files and terms you'll be working with.
- Migrations:
- Migrations are used to directly affect the columns of the database. This isn't used for putting data into the database, but instead to make new columns, tables, etc.
- Found in: database/migrations
- Views:
- Views are the files holding the HTML code that you see. Laravel uses a blade system, which essentially means that each page you see when you load your site is actually a bunch of files fitted together, like a knife block. This allows a certain amount of customization and more importantly, allows you to reuse code in numerous locations or ways. This is how so many pages have similar sidebars - the sidebar isn't included in its entirety on every page.
- Found in: resources/views
- Forms:
- This is what your users or admins will see when they want to edit the information in the database. It's important to note that without the back-end information (such as if you just put a text box on a page,) forms will do nothing.
- Found in: resources/views
- Routes:
- When you navigate to a page in your browser, the site looks at the URL and then looks at the route to see where to go next, unlike static websites where you'd go to, say, index.html and see the page that's index.html in the root directory. Routes work by (usually) going to a function in a controller. GET routes are getting the information from the site in order to display it, while POST routes are sending the information from a form back to the controller to be handled.
- Found in: routes
- Controllers:
- Controllers receive and give data. There are two main function types: GET and POST. GET generally gets information from the database and puts it together for the user to see it. This is how views are called and accessed. POST is generally used to put data into the database. Laravel has a naming convention for these for function names: GET functions generally begin with all-lowercase get (eg. getSettings, getNotifications) while POST functions usually begin with all-lowercase post (eg. postPassword, postEmail.)
- Fun fact: This method of naming functions/variables with a lowercase word and then capitalized words in programming is called camelCase.
- Found in: app/Http/Controllers
- Services:
- Services usually handle the actual placing of data into the database. While sometimes people will code the data->database handling in the Controller, it's usually better praxis to have this handling in the Service.
- Found in: app/Services
- Models:
- Models directly relate to the table in the database. We won't need to make a new model for this, since we'll just be editing an existing table, but we will need to edit one slightly.
- Found in: app/Models
Here's an analogy:
You begin your job by picking up a package of spices [the data] at the POST office [a form]. You look at your directions [the link on a form] and go along the route [route] to the restaurant worker [controller]. The package is given to the chef [service], who puts the spices [data] into the appropriate cabinets [columns in the database] in the appropriate room [table in the database.] Later, when requested by the customer [page load on a GET route], the restaurant worker [controller] gets the ingredients and puts them together. They then put the food on the plate [view] and place it on the table for the customer [you!]
Starting Out: Migrations
Planning the Migration
Before you even begin coding, you should have determined some things:
- What information do you want added?
- Is it nullable - can it be completely empty/blank?
- Does it have a default value?
- What form does this information take? Is it a short text input that should only be a few words? A full WYSIWYG (What You See Is What You Get) input? A boolean (True/false?)
- Does this need to be in a new table or does it fit in one of the existing tables? This tutorial will only cover existing tables.
I recommend looking at existing migrations if there's anything similar to the field you want to add.
Migrations have a specific way to be created in a console command! I always recommend testing on a local server (like WAMPserver or XAMPP) before you mess with the database on your live server. I also recommend looking at the documentation - it's my go to when I need to add something. It makes it easier if you include the table in the migration command, though you are able to affect multiple tables in one migration if you so desire.
Generating the Migration
Go into your console commands (I use Putty for my server and Sourcetree or VSC directly for my local, depending on if I'm using Atom or VSC as my editor.)
php artisan make:migration add_nickname_to_users_table --table=users
It's good to make the title (add_nickname_to_users_table) as descriptive as possible whilst being succinct, but remember: this will be part of the file name for the migration file.
Once you hit enter, it might take a minute to create, but it will give a nice verification saying something like:
Created Migration: 2020_08_21_104400_add_nickname_to_users_table
Now you can navigate to your database/migrations folder and see a fresh new file! If you used the form I suggested, it'll look pretty much exactly like this, but maybe with different colours:
1 <?php
2
3 use Illuminate\Support\Facades\Schema;
4 use Illuminate\Database\Schema\Blueprint;
5 use Illuminate\Database\Migrations\Migration;
6
7 class AddNicknameToUsersTable extends Migration
8 {
9 /**
10 * Run the migrations.
11 *
12 * @return void
13 */
14 public function up()
15 {
16 Schema::table('users', function (Blueprint $table) {
17 //
18 });
19 }
20
21 /**
22 * Reverse the migrations.
23 *
24 * @return void
25 */
26 public function down()
27 {
28 Schema::table('users', function (Blueprint $table) {
29 //
30 });
31 }
32 }
The two existing functions are important! up()
is what gets set up when you run php artisan migrate
later, while down()
is what's run if you ever need to roll the migration back. If you'll be working with multiple tables at once, it's generally good practice to have the down() be in reverse order of the up()
- at least, when you're working with foreign keys!
Writing the Migration
This is usually where I rely pretty heavily on the documentation and also previous migration files! For instance, if you are adding a whole new table (something a bit more advanced than this tutorial is going to go over), you'll want to make sure the new table is InnoDB
and using increments
for the id instead of the default of bigIncrements
, just to keep things uniform among the tables. Dealing with different column types can sometimes get messy, so it's best to work similarly from the start!
So. We want to make a "Nickname" for a user!
The column type for this will likely be "string." By default, Lorekeeper's migrations run the max length of strings at 191 characters, but you can set this to be different if you want a specific maximum.
As far as the column modifiers go, you'll probably want the column to be nullable()
, which means the column can be NULL - empty. While the documentation shows nullable()
as nullable($value = true)
, you can essentially leave it as nullable()
for the same effect. If you want a non-nullable column, you'll want to set a default()
. You also may want the column to be in a particular location in the table, aka directly after another column.
Those two will go in up()
- what goes in down()
will just be to reverse what we did above. Using the previous migrations as example, we will use dropColumn('nickname')
.
The final migration will look like this:
1 <?php
2
3 use Illuminate\Support\Facades\Schema;
4 use Illuminate\Database\Schema\Blueprint;
5 use Illuminate\Database\Migrations\Migration;
6
7 class AddNicknameToUsersTable extends Migration
8 {
9 /**
10 * Run the migrations.
11 *
12 * @return void
13 */
14 public function up()
15 {
16 Schema::table('users', function (Blueprint $table) {
17 $table->string('nickname', 191)->nullable()->after('name');
18 });
19 }
20
21 /**
22 * Reverse the migrations.
23 *
24 * @return void
25 */
26 public function down()
27 {
28 Schema::table('users', function (Blueprint $table) {
29 $table->dropColumn('nickname');
30 });
31 }
32 }
Now, after you save the file, when you run php artisan migrate
in your terminal, it will create a column called "nickname" after the "name" column that is a nullable string with a max length of 191 characters.
If you pull up phpmyadmin and load into the users table, you should see something like this (see image).
Reversing the Migration
If you decide you want to change something, all you have to do is run the following command in your terminal:
php artisan migrate:rollback
This will run the down()
function for you, dropping or removing the column. Note that this is destructive!! If you have data you want to save in the nickname column, you should back it up before rolling it back. Also, if you rollback too far, you may accidentally lose even more data - so be careful!
Adjusting the Existing Files
Model
To start off, you'll want to add 'nickname' to the Model so that Laravel will understand that the column exists and can be edited.