Tutorial 3 System Coding and Implementation – Part I
We introduce the basics of web application building using the Laravel framework in this tutorial. We will continue to use the “TODO list” system introduced in the last tutorial to teach you the basics of system building and implementation here. The system building phase here involves two distinct processes: setting up the back–end database, and coding the system; where coding the system can be further broken down into basic REST-ful (CRUD-based) coding implementations and more advanced coding implementations. In this tutorial, we will focus on building the database, and implementing the REST-ful codes of the system.
Set up an Dynamic Laravel Application with Database Support
Unlike the static personal website you’ve created in tutorial 1, a dynamic web application populates its content from an underly- ing database, generating different web page content according to the input from different users. In this case, a dynamic web applica- tion enables interaction with the user, and the underlying database provides support to the functionalities of the web application.
Before proceed to coding the web application, we need to first pre- pare the underlying database and establish the connection between the database and the web application. The process is divided into 2 simple steps:
Steps to Set Up the Underlying Database
1. Create the project database hosted by MySQL
2. Configure the database in Laravel to establish their connec- tion
120 planning, designing, and programming for web application
Create the Project Database in MySQL using “phpMyAdmin”
Laravel supports communication with a number of different database servers, for simplicity and the ease to manage, we will be hosting the databasing in MySQL database server, through a web interface called “phpMyAdmin”. The package is bundled in the Laragon software pre-installed on the computers in the computer lab. Refer to figure 164, open the Laragon control panel and press “Start All” or click on the elephant as indicated on the figure.
The elephant turns blue after both servers are fired up. Launch the “phpMyAdmin” interface by selecting the “Database” button as shown in figure 165:
Figure 164: Start Web and Database Server
Figure 165: Launch the “phpMyAdmin” Interface
The “phpMyAdmin” will be launched within a web browser window, in which all the database management can be carried out in this
web interface, use the username “root” to login into the database management page. Refer to figure 166, select “New” from the left sidebar of the “phpMyAdmin” homepage, from the “create database” interface on the right, key in your UID and select “utf8_unicode_ci” as the Collation, then press “Create”.
tutorial 3 system coding and implementation – part i 121
Observe there is a new database (with your UID) appear at the left sidebar of the “phpMyAdmin” web interface. The project database is now created, you can move on configuring this database connection in Laravel.
Database Configuration in Laravel
Go to the Laragon web root folder by selecting “Root” from the Laragon control panel. Open the “TutorialBase.zip” file with 7-zip, and drag the “TutorialBase” folder to the root directory. Rename the “TutorialBase” folder using your UID, such that your Laravel project’s root directory is inside “C:\laragon\www\Your_UID”.
The “TutorialBase” is a specially-configured version of Laravel 5.1 project which allows your project to run properly in this course’s pro- duction server, we shall build up our project from this base project for both the tutorials and your final project.
In Sublime Text 3, open the newly created Laravel project folder
Figure 166: Create New Database in “phpMyAdmin”
122 planning, designing, and programming for web application
(“C:\laragon\www\Your_UID”) and open the “.env” file in its root directory. Refer to figure 167, modify the database name to the database that you’ve just created (presumably your UID), set the username to be “root” and leave the password empty.
Open the database configuration file in “config/database.php” and confirm that the default database engine is set to be “mysql” as shown in figure 168:
Figure 167: Configure the Database in Laravel
The database connection has now been configured, you can move on to the next part to build up the database with tables designed in the previous tutorial.
Figure 168: Configure the Database in Laravel
Introducing Laravel Models and Database Migration
A well-designed web application is model-centric, meaning the models (for instance, users, lists, tasks, and categories) are the primary driver for implementing an application’s business logic. Fortunately, Laravel provides developers with a powerful set of
tools useful for building and managing models and their respective underlying database tables. In this section, we will walk you through the steps to create model classes using Laravel’s artisan command, create and perform database migrations, and seed the database with pre-defined records.
Create the Model Classes
While holding the “Shift” key, right-click on the newly renamed folder and select “open command window here”. You will be using this command line window throughout the tutorial to execute vari- ous Laravel Artisan commands.
Creating a model using Laravel Artisan is easy. For the demon- stration, let’s start with creating the Category model. Refer to fig- ure 169, create the Category model with the command “php artisan make:model Category –migration”. Please note that the first letter of the model name should be Capitalised.
tutorial 3 system coding and implementation – part i 123
Notice that the artisan command created 2 files at the same time: the Category.php model file, and the “create_categories_table.php” migration file. This is because a model is only useful when it is as- sociated with an underlying database table, whereas the migration file is essentially a blueprint for creating the database table associated with the model file. It is also customary in a web application frame- work to name the model file in its singular form, and the underlying table in its plural form (Category model v.s. categories table).
Figure 169: Create Category Model using Laravel Artisan
124
planning, designing, and programming for web application
Complete this by yourself before proceeding to the next section
Please create the remaining models in the TODO list web application: • Todolist model
• Task model
Pay attention to the sequence you are creating the models. You should always start with database tables without foreign keys then move on to creating tables which reference these tables in their foreign key field. In this case, the sequence in creating the models are Category → Todolist → Task, as the todolists table references the categories table, and the tasks table references the todolists table. If the models are not created in their right sequence, the migration would render into trouble!
Set up Database Migrations
Fundamentals of Migrations
With the models created, you will typically create the corre- sponding database tables, done through a fantastic Laravel feature known as migrations. Migrations offer a file-based approach to changing the structure of your database, allowing you to create
and drop tables, add, update and delete columns, and add indexes, among other tasks. Further, you can easily revert, or rollback, any changes if a mistake has been made or you otherwise reconsider the decision. Finally, because each migration is stored in a text file, you can manage them within your project repository.
In this section, we will only demonstrate the very basics of migra- tions which would enable you to get your web application started, you are encouraged to explore more of this functionality on your own if you are curious of this feature.
The migration files are within the “database/migrations” folder in the Laravel project directory. Figure 170 shows the basic structure of the “create_categories_table.php” migration file you’ve just created.
Like a model or a controller, a Laravel migration is just a stan- dard PHP class, in this case, the migration file extends the Migration class in Laravel. Take note of the two class methods, up() and down(). These have special significance in regards to migrations – the up() method defines what occurs when the migration is executed, whereas the down() method defines what occurs when the migration is re- verted. Therefore, the down() method should define what happens
when you’d like to undo the changes occurring as a result of execut- ing the up() method. Let’s first examine the “CreateCategoriesTable” migration up() method shown in figure 171:
This migration up() method is essentially used to create the “categories” table with a set of attributes. The up() method uses
the “Schema::create” command to create a “Blueprint” of the “cat- egories” table, the attributes of the “categories” table are defined
in the blueprint. In this example, the “increments” method create the primary key of the a table which is an automatically increment- ing integer; whereas the “timestamp” method creates 2 columns “created_at” and “updated_at” which will be handled by Laravel automatically when a record is created or updated in the future.
Figure 171: The Category up() Method
tutorial 3 system coding and implementation – part i 125
Figure 170: Basic Structure of A Migra- tion File
126 planning, designing, and programming for web application
There are plenty of other methods useful for creating different data types, setting data type attributes, and more. We will provide a complete list of such methods later in this section.
The down() method shown in figure 172 is straightforward – it drops (deletes in the database) the “categories” table created in the up() method.
Customise the Migration Files
Now we need to customise the migration files created by Laravel with accord to the database design of the TODO list web application. There are altogether 4 migration files need to be customised: “cre- ate_users_table”, “create_categories_table”, “create_todolists_table”, and “create_tasks_table”.
We begin with modifying the “create_users_table” migration file as shown in figure 173:
Figure 172: The Category down() Method
The “is_admin” of type boolean (true or false) and “user_image” of type string are added to the blueprint of “users” table. On top of the attribute addition, the “is_admin” attribute is assigned a default value of false, whereas the “user_image” attribute is set to be nullable.
Accordingly, we modify the “create_categories_table” migration file as shown in figure 174:
Figure 173: The Modified Users up() Method
In this case, the attribute “name” of type string is added to the blueprint of the “categories” table.
The “create_todolists_table” migration file can be modified as shown in figure 175:
tutorial 3 system coding and implementation – part i 127
Figure 174: The Modified Categories up() Method
Quite a number of attributes and references are added to the blueprint of “todolists” table. For instance, “category_id” and “user_id” are added and defined as foreign keys of the table. The “name” at- tribute of type string and “description” attribute of type text are also added to the definition.
Bear in mind that both the “categories” and the “users” table should be already created when you define the foreign key references here, otherwise the migration would run into error. Moreover, all foreign keys should be of type integer and be unsigned as demonstrated in the example. The referencing of foreign key relationship here is straightforward, first the foreign key is defined using the foreign() function, then the primary key reference is defined with the refer- ences() function, and the primary key’s parent table is defined using the on() function. The onDelete(’cascade’) function instructs the database to delete all the related record in the ’todolists’ table when the referenced “category_id” or “user_id” is deleted in the parent table.
Figure 175: The Modified Todolists up() Method
128 planning, designing, and programming for web application
Lastly, modify the “create_tasks_table” migration file as shown in figure 176:
The attribute “todolist_id” is added and defined as foreign key in the “tasks” table. Other new attributes include “name” of type string, “due” of type date, and “done” of type boolean with a default value of false.
The modified versions of migration files are available for download in the course Moodle, you can download the file (“migration.txt”) and paste into the respective migration files in your Laravel project.
Figure 176: The Modified Tasks up() Method
Perform the Database Migration
Now that we’ve prepared the migration files, it is time to execute these migration files and prepare the database tables for the TODO list web application.
Refer to figure 177, key in the artisan migration command “php artisan migrate” in the command line window and hit “Enter”. As the migrations carry on, you will be prompted with confirmations of successful execution of the migrations.
In the “phpMyAdmin” web interface, refer to figure 178, select the project database and you will find 6 tables created for you by Artisan migrations. Browse through the structure of the tables, the attributes of the tables should be identical to the blueprint in the migration files.
In addition to the 5 migration tables, Laravel also created a table called “migrations” in the database. This table is used by Laravel to keep track of the current migration version, so if you would like to advance or rollback the migrations, the migration tools would know which batch of migration files to start with.
Figure 177: Performing Artisan Migra- tion
tutorial 3 system coding and implementation – part i 129
Figure 178: Database Tables Created
130 planning, designing, and programming for web application
Define Model Relations
Having all the foreign keys defined in the migration files does not automatically make the relationships working properly. To take full advantage of the Laravel framework, you have to also define the relation- ships in the model files. In our database design, both the “categories” and the “users” table are related to the “todolists” table in a “One-to-Many” relationship, and the “todolists” table related to the “tasks” table also in a “One-to-Many” relationship. We have to code these relationships into the respective models, so that we will be able to access model properties of the other table through one’s relationship.
Start with the “Category” model. Refer to figure 179, define the relationship between the “Category” model and the “Todolist” model with the “hasMany” method. Notice here since one “Category” has many “Todolist”, the “todolists()” function is in the plural form.
Similarly, we define the “User” model relationship as shown in figure 180:
Figure 179: Category Model Relation
Figure 180: User Model Relation
It is necessary to define the inverse of a relationship in the other model. Refer to figure 181, the inverse of “hasMany” relationship is the “belongsTo” relationship.
Lastly, we define the inverse relationship between “Task” model and “Todolist” model as shown in figure 182:
tutorial 3 system coding and implementation – part i 131
Figure 181: Todolist Model Relation
Figure 182: Task Model Relation
132 planning, designing, and programming for web application
Seed the Database
Fundamentals of Database Seeding
It is helpful to populate the database with test data so that we can use these data to examine the functionalities of the web application we are creating without having to manually insert these records in the database. Luckily, Laravel has a built-in database seeder to assist you in populating the database with initial test data.
Laravel’s built-in database seeder resides in the “database/seeds” folder, you can create PHP class files which extends the “Seeder” class within the “seeds” folder, and execute the database seeding process using the “php artisan db:seed” Artisan command.
We first examine the “DatabaseSeeder.php” file in the “database/seeds” folder. As indicated in figure 183, the run() function is executed when you call the “php artisan db:seed” Artisan command. Inside this run() function, you will reference other seeder files (such as the “UserTable- Seeder” file shown in the example), and when db:seed executes, the instructions found in those seeder files will be executed as well.
Create the Seeder Files
To kick start the TODO list web application, we would like to populate each of the 4 tables with a few records. The first step is to create 4 new seeder files, one for each of the table, as shown in figure 184.
Figure 184: New Seeder Files
Figure 183: DatabaseSeeder File
We will add content to each of the seeder files one-by-one, starting with “UserTableSeeder.php”. Refer to figure 185, add the contents of the “UserTableSeeder” as shown in the figure:
The UserTableSeeder structures similarly as the “DatabaseSeeder” file, they both use the “Seeder” and the “Eloquent\Model” namespace in the file, and both contain a run() function which executes a pre- defined procedure. Except in this case, the run() function creates
2 “users” records in the database through the “User” model; this
is why the “App\User” namespace is called at the top of the file. Additionally, the “Carbon\Carbon” namespace is also called to handle the DataTime functions which are required by the timestamp() method. The create method is simple to understand, except at the password value, a “Hash::make” function is called to encrypt the password; Laravel handles this by default, so you don’t have to worry about encrypting and decrypting the password manually.
Figure 185: Contents of UserTable- Seeder File
tutorial 3 system coding and implementation – part i 133
134 planning, designing, and programming for web application
You can then add the contents to the “CategoryTableSeeder” as shown in figure 186:
The CategoryTableSeeder is similar to the UserTableSeeder, you can copy and paste most of the codes from the previous file and make the necessary adjustment in the values.
Refer to figure 187, add the content to the “TodolistTableSeeder” accordingly:
Figure 186: Contents of CategoryTable- Seeder File
The TodolistTableSeeder is a bit more complex due to the need to handle foreign key relationships. Since the foreign key relation- ships are binding, you cannot randomly assign an integer to the “category_id” and the “user_id” field, assigning a non-existing id into these foreign key fields will violate the foreign key constrains and trigger errors in seeding the database. As a result, the first portion of
tutorial 3 system coding and implementation – part i 135
Figure 187: TodolistTableSeeder
136 planning, designing, and programming for web application
the run() function retrieves the “category_id” and the “user_id” values from the database, and they can then be used in the create method as values assigned to the respective foreign key fields.
Lastly, fill in the contents of the TaskTableSeeder according to figure 188:
Very much like the migration process, database seeding should also follow a sequence in which the foreign key constrains are not violated, which means the “user” and “category” seeder files should execute first, then the “todolist” seeder file, and lastly the “task” seeder file. The sequence of which the seeder files are executed is defined in the “DatabaseSeeder.php” file.
Figure 188: Contents of TaskTable- Seeder File
Refer to figure 189, open the “DatabaseSeeder.php” file and add the marked portion into the run() function. The code defines 2 things: 1. the sequence in which the database seeding is carried out, 2. delete all the existing records in each of the 4 tables. So when the seeding is running, all existing database records will be cleared out, and
the seeding will be executed in the sequence of “user → category → todolist → task”.
For your convenience, we’ve prepared a “seeder.txt” file for you in the course Moodle, feel free to download the code and paste them into the respective database seeder files.
tutorial 3 system coding and implementation – part i 137
Figure 189: Define the Seeders Execu- tion Sequence
138 planning, designing, and programming for web application
Perform the Database Seeding
After saving all the seeder files, you can now ready to execute the
database seeding procedure.
The first step of database seeding is to rebuild the autoload files, this can be done easily using composer. Refer to figure 190, key in “composer dump-autoload” in your command line window and hit “Enter”. This will trigger composer to generate new autoload files and recognise the new database seeder files we’ve just created.
Finally, run the Laravel database seeder with the command “php artisan db:seed” as shown in figure 191:
Check the contents of each tables in “phpMyAdmin”, you can find the newly created records there!
Figure 190: Re-Build Autoload Files
Figure 191: Run Laravel Database Seeder
tutorial 3 system coding and implementation – part i 139
List of Table Builder Methods
The table builder contains a variety of column types that you may use when building your tables:
Command
$table->bigIncrements(’id’); $table->bigInteger(’votes’); $table->binary(’data’); $table->boolean(’confirmed’); $table->char(’name’, 4); $table->date(’created_at’); $table->dateTime(’created_at’); $table->decimal(’amount’, 5, 2); $table->double(’column’, 15, 8); $table->enum(’choices’, [’foo’, ’bar’]); $table->float(’amount’); $table->increments(’id’); $table->integer(’votes’); $table->json(’options’); $table->jsonb(’options’); $table->longText(’description’); $table->mediumInteger(’numbers’); $table->mediumText(’description’); $table->morphs(’taggable’); $table->nullableTimestamps(); $table->smallInteger(’votes’); $table->tinyInteger(’numbers’); $table->softDeletes(); $table->string(’email’); $table->string(’name’, 100); $table->text(’description’); $table->time(’sunrise’); $table->timestamp(’added_on’); $table->timestamps(); $table->rememberToken(); ->nullable()
->default($value) ->unsigned() ->unique()
Foreign Keys $table->foreign(’user_id’)->references(’id’)->on(’users’)->onDelete(’cascade’);
Description
Incrementing ID using a “big integer” equivalent BIGINT equivalent to the table
BLOB equivalent to the table
BOOLEAN equivalent to the table
CHAR equivalent with a length
DATE equivalent to the table
DATETIME equivalent to the table
DECIMAL equivalent with a precision and scale
DOUBLE equivalent with precision, 15 digits and 8 decimal points ENUM equivalent to the table
FLOAT equivalent to the table
Incrementing ID to the table (primary key)
INTEGER equivalent to the table
JSON equivalent to the table
JSONB equivalent to the table
LONGTEXT equivalent to the table
MEDIUMINT equivalent to the table
MEDIUMTEXT equivalent to the table
Adds INTEGER taggable_id and STRING taggable_type Same as timestamps(), except allows NULLs SMALLINT equivalent to the table
TINYINT equivalent to the table
Adds deleted_at column for soft deletes
VARCHAR equivalent column
VARCHAR equivalent with a length
TEXT equivalent to the table
TIME equivalent to the table
TIMESTAMP equivalent to the table
Adds created_at and updated_at columns
Adds remember_token as VARCHAR(100) NULL Designate that the column allows NULL values
Declare a default value for a column
Set INTEGER to UNSIGNED
Adds a unique index to an attribute
$table->integer(’user_id’)->unsigned();
140 planning, designing, and programming for web application
Walkthrough to Coding a REST-ful Application
These days it is commonplace to dedicate each application controller to managing an associated resource. For instance a controller named ListsController might be responsible for retrieving all lists, retrieving a list detail view, inserting a new list, modifying an existing list,
and deleting a list. These types of controllers are often created in such a way so as to conform to REST (representational state transfer) conventions.
We will create and implement a REST-ful ListsController in this section. In modern web application, the implementation of REST ap- proach in designing and coding a web application is central to most of the popular web frameworks available to us, Laravel included. The REST-ful application codified the way the CRUD operations (Create, Retrieve, Update, and Delete) are implemented, and greatly shortens the time needed to develop the basic functionalities of a web application.
In Laravel, the HTTP protocol and a series of well-defined URL endpoints of a REST-ful controller is pre-defined as shown in table 4:
Table 4: Lists REST-ful Controller Definitions
HTTP Method
GET GET
POST GET GET
PUT DELETE
Path
/lists /lists/new
/lists /lists/:id /lists/:id/edit
/lists/:id /lists/:id
Controller Function
lists#index lists#create
lists#store lists#show lists#edit
lists#update lists#destroy
Description
Display all TODO lists
Display an HTML form for creating a new TODO list
Create a new TODO list
Display a specific TODO list
Display an HTML form for editing an existing TODO list
Update an existing TODO list
Delete an existing TODO list
tutorial 3 system coding and implementation – part i 141
Set up the REST-ful ListsController
Remember the controller functions and route paths listed in table 4 for a REST-ful controller, Laravel has a built-in set of tools to help you create these at ease. There are 2 steps involved in setting up a REST-ful controller: 1. Create a REST-ful controller in Laravel Artisan. 2. Define a Resource controller route.
Create a REST-ful Controller
The “php artisan make:controller” command by default creates REST- ful controllers with all 7 REST-ful controller functions pre-defined so you don’t have to repeatedly creating the same set of functions for different resources.
Refer to figure 192, in the command line window, create the “ListsController” with the command “php artisan make:controller ListsController”. “ListsController” is going to be the name of the REST-ful controller we are creating, and be aware that the first letter of each word should be capitalised and the word “list” should be in its plural form.
Now open up the “ListsController.php” file in Sublime Text, it should reside in the “app/Http/Controllers” directory. A skeleton of a REST- ful controller with all 7 functions are already available for you.
Create a REST-ful Routing Rule
After the REST-ful controller is created, you have to define the REST- ful controller as a resource in the “routes.php” file. When the resource is defined, all 7 paths of the REST-ful controller will be automatically available for you.
Refer to figure 193, open up “routes.php” in the “app/Http” di- rectory, and add “Route::resource(’lists’,’ListsController’);” to the bottom of the routes file.
Figure 192: Create ListsController with Laravel Artisan
Figure 193: Define ListsController as a REST-ful Resource in routes.php
142 planning, designing, and programming for web application
Save the “routes.php” file, you are now ready to code the “Lists” REST-ful controller.
CRUD Function Demonstration – Create TODO List
The Create operation is a 2 part operation, corresponding to the “create” and the “store” functions in the REST-ful controller. The “create” function involves displaying a web form and allow the user to input data into such form, then the “store” function handles storing the input data into the database.
Display the “Create” View Page
Before actually coding the “create” function, let’s first get the logic of this “create” function straight before going into actually program the elements in the function:
Logic of “create” Function
•
•
•
Model:
1. Retrieve all “Category” records, return only the “name’ and “id” values
Controller:
1. Store the “Category” records in a variable “$categories”
2. Return the “create” view along with the “$categories”
records
View:
1. Display a web form to accept user input of: “name”, “de- scription”, and “category_id” (in the form of drop-down list using the “$categories” records)
2. Submit the user input to the “store” function when the “submit” button is clicked
It is fairly easy to code the function once the underlying logic is laid out. We first start with the model portion, then the controller, and lastly the view.
Refer to figure 194, add the “App\Category” namespace to the top of the “ListsController”. Including the “Category” model namespace allows the controller to access any of the model functions defined
within the “Category” model, including all the pre-defined Laravel Eloquent model functions and any user-defined custom model functions in the “Category” model.
Refer to figure 195, code the “create” function logic in the controller.
The “Category::lists” function is a pre-defined Laravel Eloquent model function, which essentially retrieves all records in the correspond- ing database table, and retrieves only the listed attributes. In this case, the retrieved result is an array of “categories” records, with the “name” and the “id” attribute values. You should be pretty familiar with the return view function after completing tutorial 1. In the “cre- ate” function, the return view function goes along with a parameter – the “$categories” variable, so that the view will be able to access the content of the $categories variable.
Next up, create the “lists” folder in the “resources/views” directory, and create the “create.blade.php” file within the “lists” folder. Fill in the contents of the “create” view as shown in figure 196:
You can clearly distinguish the form helpers in the view file, as they have been enclosed in the “{!! !!}” syntax. An web form al- ways starts with the “Form::open()” method and ends with the
Figure 195: lists.create Function
tutorial 3 system coding and implementation – part i 143
Figure 194: Add Category Model Namespace
144 planning, designing, and programming for web application
“Form::close()” method, the “Form::open()” method must define a route or controller action name which specifies the path in which the form submits to; in this case, the form submits to “lists.store” route. In between the open and close methods are the form elements accepting user input, and a “Form::submit()” method to submit the web form. A detailed description of all the HTML and Form helpers is provided at the end of this tutorial notes.
Save the view file and boot up the web server with the “php artisan serve” command. Preview the “lists.create” view in your browser at http://localhost:8000/lists/create. Your “lists.create” view should look like that in figure 197:
If you press the “Create List!” button now, you will be redirected to the http://localhost:8000/lists page. This is because you have not yet code the “lists.store” function, thus the page is redirected to the path pre-defined in the resource routing rule.
Figure 196: lists.create View
“Store” the TODO List in Database
The logic for the “store” function is stated below, as the “store” function only performs task to save user input into the database, the “View” element is not involved here.
Logic of “store” Function
• Model:
1. Define the fillable attributes
2. Retrieve the “Category” record corresponds to the “cate- gory_id” from the user input
3. Create a new “Todolist” record with the user input
• Controller:
1. Obtain the current “User” record using the Laravel “Auth” API
2. Create a new “Todolist” record, and assign the corre- sponding user input to the record
3. Associate the “Category” and the “User” record with the “Todolist” record
4. Save the “Todolist” in the database
5. Redirect to “lists.show” to display the newly created record
tutorial 3 system coding and implementation – part i 145
Figure 197: lists.create View in Browser
146 planning, designing, and programming for web application
Defining the fillable attributes is an extremely important step in preparing the model file before committing to programming the “store” and “update” functions for any database tables. For security reason, Laravel does not allow assigning values to a record manually, any attempt to do so would result in a “mass assignment error”.
As a result, we need to define the “fillable attributes” in the model, any input from the user in a web form should be a fillable attribute, so the system knows these attributes are supposed to be manually assigned.
To define the “fillable attributes” in the “Todolist” model, open the model file and add the line shown in figure 198:
There are 2 new namespaces required to add to the “ListsController” before proceed to program the “store” function. Refer to figure 199, add the “App\Todolist” and the “Auth” namespace to the top of
the “ListsController.php” file. The “Todolist” namespace allows the controller to access the “Todolist.php” model, whereas the “Auth” namespace allows access to the Laravel “Authentication” helper, so the controller can retrieve user information of the current user and use the information in the “store” function.
Figure 198: Add Fillable Attributes to “Todolist” Model
Add the code of the “store” function into the “store()” function of the “ListsController.php” file as shown in figure 200:
Figure 199: Add Namespace to “ListsController”
Based on the code of the “store” function, the store() function mainly does 2 things: 1. create a new “Todolist” record and fill the record with user input and “category” and “user” record associated with the model. 2. redirect to the route named “lists.show” (which in this case refers to the “show($id)” function in the “ListsController”.
tutorial 3 system coding and implementation – part i 147
Figure 200: “ListsController” store() Function
148 planning, designing, and programming for web application
CRUD Function Demonstration – Retrieve TODO List
In a REST-ful controller, the “retrieve” operation refers to 2 specific functions – “show” function which retrieves a single record, and the “index” function which retrieves a list of records. In this demonstra- tion, we will show you how both of these functions are done.
Retrieve a Single TODO List – “Show” List The logic for the “show” list function is shown below:
Logic of “show” Function
• Model:
1. Retrieve “Todolist” record based on “$id”
• Controller:
1. Get the list id parameter with the “$id” variable
2. Store the “Todolist” record in a variable “$list”
3. Return the “show” view along with the “$list” record
• View:
1. Display the content of the “$list” record: “name”, “descrip-
tion”, “category”, “created_at” and “updated_at”
Since we have already added the “Todolist” namespace to the “ListsController” when we added the “store” function, we can use the “Todolist” model functions directly in this case. Refer to figure 201, add the contents into the “show” function.
The “show($id)” function is pretty simple – retrieve the specified “Todolist” record, and return the view with the record retrieved.
Figure 201: “ListsController” show($id) Function
Blending in the $list record with the raw HTML tag is easy with Laravel’s “Blade” template engine. As you can see in the code, the value of the $list record is enclosed inside the “{{}}” syntax within a “blade.php” HTML page. Since we have already set up the relation- ship between the “Todolist” and the “Category” model previously, we are now able to conveniently use the “$list→category→name” syntax to get the name of the category without actually retrieving the name in the controller function.
Save the view file and check out the rendered output from the web browser at http://localhost:8000/lists/1, you should be able to get the web page for $list(1) as shown in figure 203:
tutorial 3 system coding and implementation – part i 149
Next, create the “show.blade.php” view file inside the “resources/views/lists” directory. Open the newly created “show.blade.php” view file, then
add the code shown in figure 202.
Figure 202: ’lists.show’ View
Figure 203: ’lists.show’ View in Browser
150 planning, designing, and programming for web application
Retrieve All TODO Lists – List “Index”
The logic for the “index” list function is shown below:
Logic of “index” Function
• Model:
1. Retrieve all “Todolist” records
• Controller:
1. Store the “Todolist” records in a variable “$lists”
2. Return the “index” view along with the “$lists” record • View:
1. Display the details of the “$lists” record in the form of a table
2. Show a series of action buttons allow the user to “edit” and “delete” the list, and add task to the list
The “index” function is extremely similar to the “show” function, except that the “index” function retrieves a list of records, and display the record in the form of a table. Start with the “index()” controller function, add the code shown in figure 204.
The all() method is a Laravel Eloquent model function intended
to retrieve all records in a given database table. In this case, the “Todolist::all()” method retrieves all todolists records in the database, regardless of whether or not the record belongs to the current user. We will get to more of the Eloquent methods in the future, allow- ing we to add more conditions to the retrieval process to filter the retrieved results.
Create the “index.blade.php” view file within the “resources/views/lists” directory. Open the newly created “lists.index” view and fill in the
code as shown in figure 205.
Figure 204: “ListsController” index() Function
The “foreach ($items as $item) · · · endforeach” syntax is frequently coupled with views needing to display a list of records obtained from the database. The statement literally means “for each record in the collection of records, do the following on each of the records”. In this case, each record produces a row in the table, and displays various content in the record along with 2 action buttons pointing to edit and delete the record.
Another thing worth noticing is the “delete” button, which in this case is wrapped inside a HTML form. Recall that the REST-ful resource requires the “delete” function to be interpreted by the routes as using the HTTP DELETE method, this thus need to be specified in the view. To meet the HTTP method requirement, the button is wrapped inside a form, and the “method=>delete” is identified from there.
tutorial 3 system coding and implementation – part i 151
Figure 205: ’lists.index’ View
152 planning, designing, and programming for web application
Check out the “lists.index” view in its works via http://localhost:8000/lists, the list should look similar to that in figure 206:
Figure 206: ’lists.index’ View in Browser
CRUD Function Demonstration – Update TODO List
Just like the “Create” operation, the “Update” operation also involves 2 parts of REST-ful functions – the “edit” function to retrieve the record and display in a form for the user to make changes, and the “update” function which submits the changes to the database.
Display the “Edit” View Page
The logic to the “edit” function is shown below:
Logic of “edit” Function
• Model:
1. Retrieve the “Todolist” record using $id
2. Retrieve all “Category” records, return only the “name’ and “id” values
• Controller:
1. Store the “Todolist” record in a variable “$list”
2. Store the “Category” records in a variable “$categories”
3. Return the “edit” view along with the “$list” and “$cate- gories” records
• View:
1. Display a web form of the list for user to edit the TODO
list content
2. Display the original $list content as default value in the form
As mentioned earlier, both the “update” and “delete” operation require first retrieving the given record before carrying on with the “update” or “delete” operation, that’s why the $id is required for both these functions just like that for the “show” function (retrieve operation).
Start with coding the controller function, fill in the edit($id) function with the code shown in figure 207:
You should already be quite familiar with programming the con- troller function logics by now, in fact, there are only a few Eloquent
tutorial 3 system coding and implementation – part i 153
154 planning, designing, and programming for web application
Figure 207: “ListsController” edit($id) Function
model functions and return methods used repeatedly in a conven- tional REST-ful controller. In the case of the edit($id) function, the “find” Eloquent model is used to retrieve the TODO list record, then the “lists.edit” view is returned along with the $list and the $cate- gories variable. Pay attention here within the “with” function is an
Figure 208: ’lists.edit’ View
tutorial 3 system coding and implementation – part i 155
array of 2 variables to be passed on to the view; the syntax here is a bit different then that when only 1 variable is used.
Next, create the “edit.blade.php” view file within the “resources/views/lists” directory. Open the newly created view file and fill in the content
shown in figure 208:
The “lists.edit” view is fairly similar to that of the “lists.create” view, both having a web form for the “Todolist” record. There are 4 main difference between the “create” and the “edit” form:
1. The “edit” form is bind to an existing “Todolist” record, therefore, the “Form::model” method is used instead of the “Form::open” method. The “Form::model” method allows the web form’s con- tent to be pre-populated based on the contents of a model. For instance, the form will display the original contents of the $list record when the “Form::model” method is used.
2. The form submits to the “lists.update” route, along with the id parameter of the $list variable
3. The submitted form is using the “HTTP PUT” method instead of the “POST” method
4. The “category_id” is used as the default value in the Category drop-down list
Save the files and check out the “edit” page at http://localhost:8000/lists/1/edit, the page should like somewhat like that in figure 209. Notice the web
form is pre-populated with the contents from the original “TODOlist”
record.
Figure 209: ’lists.edit’ View in Browser
156 planning, designing, and programming for web application
“Update” the TODO List in Database
The logic of the “Update” function is as follows:
Logic of “update” Function
• Model:
1. Retrieve the “Todolist” record using $id
• Controller:
1. Store the “Todolist” record in a variable “$list”
2. Update the $list content using user input
3. Redirect to route “lists.show” to display the updated record
The update function is extremely easy to handle as there’s only a few lines of code required to update the record. Refer to figure 210, fill in the code for the “update” function as shown in the figure.
The “$request->all()” is a simple and easy way to assign all user input to a model, useful when no additional value assignment or relation- ships are needed to be handled. Be careful the input name you used in the view file should match the name of the model attributes when you use the “$request->all()” method in your code.
Now, save the files and test your “update” function in the browser, the “update” function should be working now.
Figure 210: “ListsController” up- date($id) Function
CRUD Function Demonstration – Delete TODO List
The “delete” operation is handled by a “destroy” function in Laravel. The logic of the “destroy” function is shown below:
Logic of “destroy” Function
• Model:
1. Retrieve the “Todolist” record using $id
• Controller:
1. Store the “Todolist” record in a variable “$list” 2. Delete the $list record from database
3. Redirect to route “lists.index”
Refer to figure 211, fill in the “destroy” function with the code shown in the figure.
The “delete” method is used to remove the record completely in the database. Now save the file and browse to http://localhost:8000/lists, try delete a few records by clicking at the “Delete” button to verify if the function is actually working out.
Figure 211: “ListsController” de- stroy($id) Function
tutorial 3 system coding and implementation – part i 157