Tutorial: Adding Fields to Users/Characters/Etc

From Lorekeeper Wiki
Revision as of 13:38, 31 October 2020 by Preimpression (talk | contribs) (Finishing up for the day.)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

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 Characters, though you can implement the same basic logic in adding fields to items, users, 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:

  1. What information do you want added?
    1. Is it nullable - can it be completely empty/blank?
    2. Does it have a default value?
  2. 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?)
  3. 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 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_characters_table --table=characters

It's good to make the title (add_nickname_to_characters_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_10_31_180919_add_nickname_to_characters_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 AddNicknameToCharactersTable extends Migration
 8 {
 9     /**
10      * Run the migrations.
11      *
12      * @return void
13      */
14     public function up()
15     {
16         Schema::table('characters', 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('characters', 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 character!

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 AddNicknameToCharactersTable extends Migration
 8 {
 9     /**
10      * Run the migrations.
11      *
12      * @return void
13      */
14     public function up()
15     {
16         Schema::table('characters', 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('characters', 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 in the "characters" table called "nickname" after the "name" column that is a nullable string with a max length of 191 characters.

Nickname column between Name and Is_Gift_Art_Allowed columns.

If you pull up phpmyadmin and load into the characters 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!

Setting It Up

I always need to plan things out before I can get going. Some things you'll want to make sure to decide pretty early on, using nicknames as an example:

  • Can users edit their character's nicknames?
  • Do only characters get nicknames or can MYOs also have them?
  • Do characters get created with nicknames?
  • Do MYOs get created with nicknames?
  • Should nicknames be included in the Character Masterlist?
  • Where else should nicknames be visible?
  • Do you have any Accessors you'd like to include this? (Things like displayName etc)

For the purposes of this tutorial, I'll go over all of these.

Model

Fillable

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. If you navigate to app/Models/Character there will be a file called Character.php. Open this up and take it all in. Go to protected $fillable and add , 'nickname' after 'trade_id' or whatever you might have there. It doesn't matter where it's put, as long as it's there, separated from the one before (or after) it with a comma.

Adding the column to fillable means that Laravel will understand that it's a part of the database that you want users, admins, etc to be able to edit.

Accessor

If you want the nickname to be displayed in any fun way, you can add an Accessor. Accessors are set in functions that are named like so: getDisplayNameAttribute(). To view the returned value from this function, you would use {!! $character->displayName !!} on a page that $character is defined on. I'll simply add the nickname to a character's display name - the getDisplayNameAttribute() function.

285     /**
286      * Displays the character's name, linked to their character page.
287      * Also includes their nickname, if set.
288      *
289      * @return string
290      */
291     public function getDisplayNameAttribute()
292     {
293         return '<a href="'.$this->url.'" class="display-character">'.$this->fullName.'</a>'. (isset($this->nickname) ? ' ('.$this->nickname.')' : '' );
294     }

When it mentions $this , that is referring to the model in question - the Character model. When the character has a nickname set, it will be added in parentheses behind the name, after the link. So a character named Julius with the nickname Jules will appear as Julius (Jules).

Validation Rules

Also, you may want to add some validation rules for the nickname! I've added the following to $createRules, $updateRules, and $myoRules since I think both characters and MYOs should be able to have nicknames, and they should be allowed to be added during character creation.

'nickname' => 'nullable|between:3,25',

This allows the field to be nullable and also makes it only valid between 3 and 25 characters. This can be used in conjunction with the 191 string length we set up in our migration, though it should never be larger than the max length you used for the column! If it is and a user attempts a super-long nickname, the database will yell at them about truncation and you will have unhappy, confused users.

New Characters/MYOs

For nicknames to be set upon character and MYO creation, you'll have to look at the following:

  • The form already exists in the resources/views/admin/masterlist/create_character.blade.php file.
  • The route is already set up, since we're using an existing form!
  • The controller, app/Http/Controllers/Admin/Characters/CharacterController.php
  • The service, app/Services/CharacterManager.php