Web Lab Manual
Web Lab Manual
CSC336-Web Technologies
Table of Contents
2
Lab # Main Topic Page
#
Lab 01 HTML Basics 4
Lab 02 Working with HTML Links and tables 10
Lab 03 HTML forms 16
Lab 04 CSS (Cascading Style Sheet) Basics 22
Lab 05 Designing page layout using DIV, and CSS 31
Lab 06 JavaScript Basics 40
Lab 07 JavaScript Timers 48
Lab 08 JavaScript Form Validation 55
Lab 09 Mid Term Exam
Lab 10 PHP Basics 58
Lab 11 Laravel Setup and Basics 66
Lab 12 Laravel Blade Templating 79
Lab 13 Laravel and MySql 92
Lab 14 CRUD Operation 103
Lab 15 Final Term Exam
3
Lab 01
HTML Basics
Objective:
• After this lab the students should be able to understand the use of markup language “HTML” and
its basic tags.
Activity Outcomes:
The activities provide hands-on practice with the following topics
• Design basic web page using HTML Tags
• Add text formatting tags
• Add lists to web pages
• Add images and videos to the web pages
Instructor Note:
As pre-lab activity, read Chapter 1, 2 from the textbook “Web Design Playground: HTML & CSS the
Interactive Way 1st Edition, April 2019 by Paul McFedries”.
1) Useful Concepts
TAG Description
Inserts an image
<img src=”[Link]”>
4
<video
Inserts Video
src=”abc.mp4”>
Order list
<ol></ol>
Adding list items
<li> </li>
Unoredered list
<ul>
tag defines a description list.
<dl>
defines terms/names
<dt>
describes each term/name
<dd>
An inline frame is used to embed another document within the current HTML
document.
<iframe>
5
2) Solved Lab Activities
Sr. No Allocated Time Level of Complexity CLO Mapping
Activity 1 30 Minutes Low CLO-4
Activity 2 30 Minutes Low CLO-4
Activity 1
Solution
<html>
<head>
<title>Home</title>
</head>
<body bgcolor="#98E0F0">
<h1><font color="#1322D6"> COMSATS University Islamabad</font>
</h1>
<hr width="100%" color="#030303" size="4" />
<a href="[Link]"> click here </a><!-- Write your comments here -->
</body>
</html>
6
Output:
Activity 2:
Add list of topics, images and videos to your website
Solution
<html>
<head>
<title>Home</title>
</head>
<body bgcolor="#98E0F0">
<h1><font color="#1322D6"> COMSATS University Islamabad </font>
</h1>
<hr width="100%" color="#030303" size="4" />
<Center><p><h2><b><pre> Home Department Admissions Academics
Exams</pre></b></h2> </p> </center>
<hr width="100%" color="#030303" size="4" />
<ol type="I" start="4">
<li> computer </li>
<li> mouse </li>
<li> keyboard </li>
</ol>
<br />
<dl>
<dt>Coffee</dt>
<dd>- black hot drink</dd>
<dt>Milk</dt>
7
style="width:304px;height:228px;">
<iframe width="420" height="315" src="[Link]
joriayTNmwQ?autoplay=1">
</iframe>
</body> </html>
Output
Lab Task 1
Learn and try different tags and formatting options on your webpage of Comsats.
Lab Task 2
Create a webpage for Comsats library. Add lists and apply text formatting to your page. use videos and
images of the library and then add them to your page.
Lab Task 3
Use inline styling to make the webpage created in lab task 2, more aesthetic.
8
Lab 02
Working with HTML Links and tables
Objective:
After this lab the students should be able to add linking information, creating multiple pages, and
navigating in a website and add tables in web pages.
Activity Outcomes:
To familiarize the students with
• Internal links
• External links
• In-page references
• use of tables in a web page
Instructor Note:
As pre-lab activity, read Chapter 3 from the textbook “Web Design Playground: HTML & CSS the
Interactive Way 1st Edition, April 2019 by Paul McFedries”.
1) Useful Concepts
TAG Description
9
in an HTML table
Activity 1:
Use the page you created in the first lab and add the following linking information
• Create links to home, departments, admission and exams pages of CUI Islamabad campus
Solution:
<html>
<head>
<title>Home</title>
</head>
<body bgcolor="#98E0F0">
<h1><font color="#1322D6"> COMSATS University Islamabad </font>
</h1>
<hr width="100%" color="#030303" size="4" />
10
</html>
Output
Activity 2:
Create a table to add the add basic html table including the details of Company, Contact, and Country.
Solution:
<!DOCTYPE html>
<html>
<style>
table, th, td {
border:1px solid black;
}
</style>
<body>
<table style="width:100%">
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
11
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
</table>
</body>
</html>
Output
Activity 3:
Create a table as shown in the figure given below:
Solution:
<table>
<thead>
<tr>
<th colspan="2">October</th>
<th colspan="2">November</th>
12
</tr>
</thead>
<tbody>
<tr>
<td>Sales</td>
<td>Profit</td>
<td>Sales</td>
<td>Profit</td>
</tr>
<tr>
<td>$200,00</td>
<td>$50,00</td>
<td>$300,000</td>
<td>$70,000</td>
</tr>
</tbody>
<tfoot>
<tr>
<th colspan= "4">November was more produstive</th>
</tr>
</tfoot>
</table>
Output
13
3) Graded Lab Tasks
Note: The instructor can design graded lab activities according to the level of difficult and complexity
of the solved lab activities. The lab tasks assigned by the instructor should be evaluated in the same lab.
Lab Task 1
Create in-page reference to the list created in the body and marks the locations accordingly.
Lab Task 2
Use tables to create a page layout given below that displays your profile (Persional Homepage)
14
Lab 03
HTML FORMS
Objective:
To familiarize the students with the HTML forms and different input tags.
Activity Outcomes:
After this lab the students should be able to understand
• HTML input tags
• HTML Forms
Instructor Note:
As pre-lab activity, read Chapter 3 from the textbook “Web Design Playground: HTML & CSS the
Interactive Way 1st Edition, April 2019 by Paul McFedries”.
1) Useful Concepts
HTML forms are used to pass data to a server. A form can contain input elements like text fields,
checkboxes, radio-buttons, submit buttons and more. A form can also contain select lists, textarea,
fieldset, legend, and label elements. The <form> tag is used to create an HTML form.
<form>
input elements
</form>
The <form> tag
The <form arguments> ... </form> tag encloses form elements (and probably other elements as well).The
arguments to form tell what to do with the user input
action="url" (required)
Specifies where to send the data when the Submit button is clicked
method="get" (default)
Form data is sent as a URL with ?form_data info appended to the end
method="post"
Form data is sent in the body of the URL request
target="target" . Target tells where to open the page sent as a result of the request.
Input Tags
There are many input tags in the forms.
Text input
A text field:
15
<input type="text" name="textfield" value="with an initial value" /> A multi-line text field
<textarea name="textarea" cols="24" rows="2">Hello</textarea>
A password field:
<input type="password" name="textfield3" value="secret" />
Buttons
A submit button:
<input type="submit" name="Submit" value="Submit" /> A reset button:
<input type="reset" name="Submit2" value="Reset" /> A plain button:
<input type="button" name="Submit3" value="Push Me" />
Radio Buttons
Radio buttons:
<input type="radio" name="radiobutton" value="myValue1" /> male<br>
<input type="radio" name="radiobutton" value="myValue2” checked="checked" />female
Checkboxes
<input type="checkbox" name="checkbox" value="checkbox" checked="checked">
Drop-down menu
<select name="select">
<option value="red">red</option>
<option value="green">green</option>
<option value="BLUE">blue</option>
</select>
HTML5 is the current version of THML and still under development. HTML5 enhances HTML form not
only by providing new attributes to existing elements and but also provide new elements which can be
added to the HTML forms.
HTML5 attributes for existing elements Required: make an input field must to fill Pattern: used to
validate user’s input Readonly: makes an element read-only Disabled: is used to make an input field
disabled
Autocomplete: adds autocomplete functionality to input fields
16
Number input field: makes an input field to accept only numeric values
<input type=”number”>
Activity 1:
Make a form with name, gender (use radio buttons) , password and submit form option. Use text box
for input fields and buttons for submit option.
Solution:
<html>
<head>
<title>Get Identity</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-
1">
</head>
<body>
<p><b>Who are you?</b></p>
<form method="post" action="">
<p>Name:
<input type="text" name="name">
</p>
<p>Password:
<input type="password" name="password">
</p>
<p>Gender:
<label><input type="radio" name="gender" value="m" />Male<label>
<label><input type="radio" name="gender" value="f" />Female</label>
</p>
<p>:
<input type="submit" name="submit" value="Login" />
17
Output:
Activity 2:
Solution:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form>
<h1>Register</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email"
id="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw"
id="psw" required>
18
repeat" id="psw-repeat" required>
<hr>
<p>By creating an account you agree to our <a href="#">Terms &
Privacy</a>.</p>
</form>
</body>
</html>
Output:
Note: The instructor can design graded lab activities according to the level of difficult and complexity
of the solved lab activities. The lab tasks assigned by the instructor should be evaluated in the same lab.
Lab Task 1
Write the HTML code for JOB application form of CUI (find the complete job application form
from CUI web site)
19
Lab Task 2
Design the web template given below using Tables and forms concept in HTML. Moreover add colors to
the fields and tables as mentioned [Link] links to connect face book, twitter, and terms & conditions.
Grey
Light
Black Dark Blue blue
White
fields
Green
button
20
Lab 04
CSS (Cascading Style Sheet) Basics
Objective:
To familiarize the students with the cascading style sheets.
Activity Outcomes:
After this lab the students should be able to apply CSS to the web pages.
Instructor Note:
As pre-lab activity, read Chapter 4 from the textbook “Web Design Playground: HTML & CSS the
Interactive Way 1st Edition, April 2019 by Paul McFedries”.
1) Useful Concepts
CSS(Cascading Style Sheet)
CSS stands for Cascading Style Sheets. It is a way to style HTML webpages. A style sheet is the
presentation of an HTML document. CSS is a style language that defines layout of HTML documents.
For example, CSS covers fonts, colours, margins, lines, height, width, background images, advanced
positions and many other things. CSS can be written either inside the html tags (i.e. Inline), in the
<head></head> section of an HTML document (i.e. Internal) or in a separate CSS File (i.e. External).
For inline styling CSS is written inside the style attribute of a tag. For example,
<tag style=”property:value”></tag>
For Internal styling, CSS is written into the head section of the HTML document. For example,
<style>
.class
property:value;
</style>
21
For external styling, CSS is written as a separate file and the file is saved with an extension .css. In
external style sheets the style tags are not necessary. Whereas, external CSS follow the same structure as
the Internal CSS does.
Basic CSS Properties Font Properties
Font Family Font Style Font Variant Font Weight
Word Spacing Letter Spacing Text Decoration Vertical Alignment Line Height
Box Properties
Internal CSS:
<html>
<head>
<title>Internal CSS</title>
<style> h1{color:#FF0000; font-family:Calibri; font-size:36px
}
</style>
</head>
<body>
<h1>This heading is styled with CSS</h1>
</body>
</html>
External CSS:
22
2) Solved Lab Activities
Sr. No Allocated Time Level of Complexity CLO Mapping
Activity 1 15 Minutes Low CLO-4
Activity 2 45 Minutes High CLO-4
Activity 1:
Apply border and padding properties on the different paragraphs of an HTML document.
Solution:
<!DOCTYPE html>
<html>
<head>
<style>
p {
border: 2px solid powderblue;
padding: 30px;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
</body>
</html>
23
Output:
Activity 2:
Use the HTML page created in Lab 3 (Signup page) and create an external style sheet that styles the
elements of the page including the style for
Solution:
External [Link]
body {
background-color: lightblue;
}
h1 {
color: navy; margin-left: 20px; font-family: verdana;
font-size: 50px;
}
#para1 {
text-align: center; color: red;
}
.center {
text-align: center; color: yellow; }
<!DOCTYPE html>
<html>
<style>
body {font-family: Arial, Helvetica, sans-serif;}
* {box-sizing: border-box}
24
input[type=text], input[type=password] {
width: 100%;
padding: 15px;
margin: 5px 0 22px 0;
display: inline-block;
border: none;
background: #f1f1f1;
}
input[type=text]:focus, input[type=password]:focus {
background-color: #ddd;
outline: none;
}
hr {
border: 1px solid #f1f1f1;
margin-bottom: 25px;
}
button:hover {
opacity:1;
}
25
/* Add padding to container elements */
.container {
padding: 16px;
}
/* Clear floats */
.clearfix::after {
content: "";
clear: both;
display: table;
}
/* Change styles for cancel button and signup button on extra small
screens */
@media screen and (max-width: 300px) {
.cancelbtn, .signupbtn {
width: 100%;
}
}
</style>
<body>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email"
required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw"
required>
<label>
<input type="checkbox" checked="checked" name="remember"
style="margin-bottom:15px"> Remember me
</label>
26
<div class="clearfix">
<button type="button" class="cancelbtn">Cancel</button>
<button type="submit" class="signupbtn">Sign Up</button>
</div>
</div>
</form>
</body>
</html>
Output:
Note: The instructor can design graded lab activities according to the level of difficult and complexity of
the solved lab activities. The lab tasks assigned by the instructor should be evaluated in the same lab.
27
Lab Task 1
Design the web template given below using tables and external CSS
28
Lab Task 2
Design the web template given below using tables and external CSS
29
Lab 05
Designing page layout using DIV and CSS
Objective:
To familiarize the students with the use of Div’s and the use of CSS for designing page layout
Activity Outcomes:
Instructor Note:
As pre-lab activity, read Chapter 4 from the textbook “Web Design Playground: HTML & CSS the
Interactive Way 1st Edition, April 2019 by Paul McFedries”.
1) Useful Concepts
The div tag is used to define a division or section in an HTML document. It visually, allows us to
make containers that can be formatted. It can be declared as: <div>……</div>. We use div and CSS to
design a page layout. The div tag is used to represent sections in a page and CSS is used to style these
sections. We can describe the process of designing a page as
• Determine the requirements of the site
• Group the required information
• Make a site map
• Identify key elements for each page
• Decide about the arrangement of information on each page
• Translate the design into code
Activity 1:
Use div and CSS properties to design a responsive form that contains First name, Last Name, Country
(dropdown), Subject and submit button.
30
Solution:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {
box-sizing: border-box;
}
label {
padding: 12px 12px 12px 0;
display: inline-block;
}
input[type=submit] {
background-color: #04AA6D;
color: white;
padding: 12px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
float: right;
}
input[type=submit]:hover {
background-color: #45a049;
}
.container {
border-radius: 5px;
background-color: #f2f2f2;
padding: 20px;
}
.col-25 {
float: left;
width: 25%;
margin-top: 6px;
31
}
.col-75 {
float: left;
width: 75%;
margin-top: 6px;
}
/* Responsive layout - when the screen is less than 600px wide, make
the two columns stack on top of each other instead of next to each
other */
@media screen and (max-width: 600px) {
.col-25, .col-75, input[type=submit] {
width: 100%;
margin-top: 0;
}
}
</style>
</head>
<body>
<h2>Responsive Form</h2>
<p>Resize the browser window to see the effect. When the screen is
less than 600px wide, make the two columns stack on top of each other
instead of next to each other.</p>
<div class="container">
<form action="/action_page.php">
<div class="row">
<div class="col-25">
<label for="fname">First Name</label>
</div>
<div class="col-75">
<input type="text" id="fname" name="firstname"
placeholder="Your name..">
</div>
</div>
<div class="row">
<div class="col-25">
<label for="lname">Last Name</label>
</div>
32
<div class="col-75">
<input type="text" id="lname" name="lastname"
placeholder="Your last name..">
</div>
</div>
<div class="row">
<div class="col-25">
<label for="country">Country</label>
</div>
<div class="col-75">
<select id="country" name="country">
<option value="Pakistan">Pakistan</option>
<option value="Canada">Canada</option>
<option value="usa">USA</option>
</select>
</div>
</div>
<div class="row">
<div class="col-25">
<label for="subject">Subject</label>
</div>
<div class="col-75">
<textarea id="subject" name="subject" placeholder="Write
something.." style="height:200px"></textarea>
</div>
</div>
<div class="row">
<input type="submit" value="Submit">
</div>
</form>
</div>
</body>
</html>
Output:
33
Activity 2:
Use div and CSS properties to design a page layout that contains
• a header section to display the title, style this title with CSS
• a form container that contains a registration form, use CSS to style the elements of the form
• a footer section
Solution:
External CSS
body {
background-color: lightblue;
}
h1 {
color: navy; margin-left: 20px; font-family: verdana;
font-size: 50px;
}
#para1 {
text-align: center; color: red;
}
.center {
text-align: center; color: yellow;
}
<html>
<head>
<title>Using divs</title>
</head>
<body>
<div>
<div style="width:100px;backround-color:gray">First</div>
34
<div style="width:100px;backround-color:red">second</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<style>
body {font-family: Arial, Helvetica, sans-serif;}
* {box-sizing: border-box}
input[type=text]:focus, input[type=password]:focus {
background-color: #ddd;
outline: none;
}
hr {
border: 1px solid #f1f1f1;
margin-bottom: 25px;
}
button:hover {
opacity:1;
}
35
/* Extra styles for the cancel button */
.cancelbtn {
padding: 14px 20px;
background-color: #f44336;
}
/* Clear floats */
.clearfix::after {
content: "";
clear: both;
display: table;
}
/* Change styles for cancel button and signup button on extra small
screens */
@media screen and (max-width: 300px) {
.cancelbtn, .signupbtn {
width: 100%;
}
}
</style>
<body>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email"
required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw"
36
required>
<label>
<input type="checkbox" checked="checked" name="remember"
style="margin-bottom:15px"> Remember me
</label>
<div class="clearfix">
<button type="button" class="cancelbtn">Cancel</button>
<button type="submit" class="signupbtn">Sign Up</button>
</div>
</div>
</form>
</body>
</html>
Output:
37
Note: The instructor can design graded lab activities according to the level of difficult and complexity
of the solved lab activities. The lab tasks assigned by the instructor should be evaluated in the same lab.
Lab Task 1
Design the web template given below using tables and external CSS
Lab Task 2
Design the web page for Comsats Alumni using External CSS.
Lab 06
38
JavaScript Basics
Objective:
To familiarize the students with Java Script.
Activity Outcomes:
Instructor Note:
As pre-lab activity, read Chapter 8 from the textbook “Web Programming with HTML5, CSS, and
JavaScript Pap/Psc John Dean, Year 2018
1) Useful Concepts
JavaScript is used in millions of Web pages to improve the design, validate forms, detect
browsers, create cookies, and much more. JavaScript is the most popular scripting language on
the internet, and works in all major browsers, such as Internet Explorer, Mozilla, Firefox,
Netscape, Opera.
Variables in JavaScript:
JavaScript provides numbers, string, boolean, and null variable types. JavaScript is a loosly
typed language. var keyword is used to declare a variable. We can declare a variable in
JavaScript as
var name=’Asad’;
Operats in JavaScript:
□ Assignment Operator: =
□ Arithmetic Operators: +, - , *, /, %, ++, --
□ Logical Operators: &&, ||, !
□ Comparison Operators: ==, ===, !=, !==, <, >, <=, >=
39
Input/output in JavaScript:
□ write(); is used to write on browser
o [Link](“hello world”)
o [Link](a)
□ prompt(); is used to take input from users
o var num = prompt(“Please Enter a Number”, 0)
□ alert(): used to show an alert box
Defining a function :
function functionName([parameters])
{
[statements]
}
Conditional statements:
If statement if (condition) statement
or
if(condition)
{ statements } If-else statement if(condition)
{statement} else
{statements}
Loops in JavaScript:
For loop
for(var i=1; i==10; i==)
{
[Link](“hello world”)
}
While loop
While(condition)
{
}
Do-while loop
do
{
}
while(condition)
40
Sr. No Time Allocated Complexity CLO-Mapping
Activity 1 10 Minutes Medium CLO-4
Activity 2 10 Minutes Medium CLO-4
Activity 3 10 Minutes Medium CLO-4
Activity 4 10 Minutes Medium CLO-4
Activity 5 10 Minutes Medium CLO-4
Activity 1:
Use JS to take input from user to enter a number and display the entered number by clicking on a
button “Tryit”.
Solution:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
function myFunction() {
var x = [Link]("myNumber").value;
[Link]("demo").innerHTML = x;
}
</script>
</body>
</html>
Output:
41
Activity 2:
Use JS to get the placeholder text of the search field by Clicking the button Try it
<p id="demo"></p>
<script>
function myFunction() {
var x = [Link]("mySearch").placeholder;
[Link]("demo").innerHTML = x;
}
</script>
</body>
</html>
Output:
42
Activity 3:
Use JS to write extra large or extra small numbers in exponent or scientific notation.
e.g 123e5 = 12300000 or 123e-5 = 0.00123
<h2>JavaScript Numbers</h2>
<p id="demo"></p>
<script>
let x = 123e5;
let y = 123e-5;
[Link]("demo").innerHTML = x + "<br>" + y;
</script>
</body>
</html>
Output:
43
Activity 4:
Use JS Date Function to display the date and time on HTML document.
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1">
<title>Today's Date</title>
</head>
<body>
<script>
let d = new Date();
[Link] = "<h1>Today's date is " + d + "</h1>"
</script>
</body>
</html>
Output:
44
Activity 5:
Use JS Input/output, variables, Functions, Conditional statements to create a game. Get a random
number using [Link] function in the JS. In the game it asks user to enter a number. If the
entered number matches the randomly generated number it generates an alert you won else it displays
the actual number.
Solution:
<html>
<head>
<title>Using If condition</title>
<script language="javascript">
function playGame()
{
var res=[Link]([Link]()*10)
var num=prompt("Pleae a number",0)
if(num==res)
[Link]("You Won")
else
[Link]("Your loss, correct Answer is",res)
}
</script>
</head>
<body>
<p onClick="playGame()">Play the Game</p>
</body>
</html>
45
Output:
Note: The instructor can design graded lab activities according to the level of difficult and complexity
of the solved lab activities. The lab tasks assigned by the instructor should be evaluated in the same lab.
• Write a javascript function which displays a question in prompt box and gets its answer. If the
answer is correct then shows a success message otherwise displays a error message.
• Write javascript code which asks users to enter a number, a message and displays that message
for the number of times as entered by the user.
Lab Task 4:
Lab 07
46
JavaScript Timers
Objectives:
To familiarize students with the concepts of JavaScript Animation using JavaScript Timers.
Activity Outcomes:
After this lab, the students should be able to understand the purpose and
• use of JavaScript Timers.
• Write timer functions in html for creating Website Carousel.
Instructor Note:
As pre-lab activity, read Chapter 8 from the textbook “Web Programming with HTML5, CSS, and
JavaScript Pap/Psc John Dean, Year 2018. And the website [Link]
for detailed functionalities.
1) Useful Concepts
A timer is a function that enables us to execute a function at a particular time.
Using timers, you can delay the execution of code so that it does not get done at the exact moment an
event is triggered or the page is loaded. For example, you can use timers to change the advertisement
banners on your website at regular intervals, or display a real-time clock, etc. There are two timer
functions in JavaScript: setTimeout() and setInterval().
setTimeout()
The setTimeout() method calls a function or evaluates an expression after a specified number of
milliseconds. The function is only executed once. If you need to repeat execution, use
the setInterval() method. We use the clearTimeout() method to prevent the function from running.
This function accepts two parameters: a function, which is the function to execute, and an optional delay
parameter, which is the number of milliseconds representing the amount of time to wait before executing
the function (1 second = 1000 milliseconds).
clearTimeout()
The clearTimeout()method clears a timer set with the setTimeout() method. The ID value returned by
setTimeout()is used as the parameter for the clearTimeout() method.
47
If the function has not already been executed, you will be able to stop the execution by calling the
clearTimeout() method.
Syntax: clearTimeout(id_of_settimeout)
setInterval()
The setInterval() function executes a function or specified piece of code repeatedly at fixed time intervals.
The setInterval() method will continue calling the function until the
clearInterval() is called, or the window is closed. The ID value returned by setInterval() is used as the
parameter for the clearInterval() method.
This function also accepts two parameters: a function, which is the function to execute, and interval,
which is the number of milliseconds representing the amount of time to wait before executing the function
(1 second = 1000 milliseconds).
clearInterval()
The clearInterval() method clears a timer set with the setInterval () method. The ID value returned by
setInterval() is used as the parameter for the clearInterval() method.
Then you will be able to stop the execution by calling the clearInterval() method.
clearInterval(id_of_setinterval );
Activity 1:
In first activity of this lab, we will learn how to use setTimeOut() method to display a text message after
a delay of 3 sec.
48
Solution:
Activity 2:
In second activity of this lab, we will learn how to use clearTimeOut() method to stop the execution of a
function before it is activated.
Solution:
Activity 3:
49
In first activity of this lab, we will learn how to use setTimeOut() method to display a text message after
a delay of 3 sec. In third activity of this lab, we will learn how to use setInterval() method for creating a
clock which displays current time by updating it against each second.
Solution:
50
Activity 3:
In forth activity of this lab, we will learn how to use clearInterval() method for stop the clock at any
particular moment within its updating.
Solution:
Note: The instructor can design graded lab activities according to the level of difficult and complexity
of the solved lab activities. The lab tasks assigned by the instructor should be evaluated in the same lab.
Lab Task 1
Create a Website Carousel using JavaScript for a responsive animal history web page with its layout for
different screen sizes as provided below. Following are the supplementary details about different sections
of the page:
1- The task should use bootstrap classes to create layout for Animal History banner, Image Slider
and Animal description sections of the web page. Students can only use [Link] as a third-party
CSS library.
2- Students are supposed to write a JavaScript code for imageSlider with Play and Pause buttons.
Slider should stop when Pause button is pressed and start when Play button is clicked.
51
3- It is pertinent to note that in descriptive sections of different animals, location of image and
description changes with different screen sizes.
Medium Screen
52
Large Screen
53
54
Lab 08
JavaScript Form Validation
Objective:
This lab will introduce you to regular expressions (REGEX) and its practical implementation by
demonstrating the use of regular expressions in different views.
Activity Outcomes:
After this lab the students should be able to understand Java Script basics and to validate the form using
Java Script.
Instructor Note:
As pre-lab activity, read Chapter 9 from the textbook “Web Programming with HTML5, CSS, and
JavaScript Pap/Psc John Dean, Year 2018.
1) Useful Concepts
A regular expression is an object that describes a pattern of characters. Regular expressions are nothing
more than a sequence or pattern of characters itself. They provide the foundation for pattern-matching
functionality. They are used to perform pattern-matching and "search- and-replace" functions on text.
Following link is helpful in creating regular expressions of your requirements.
[Link]
55
Activity 1:
Develop and demonstrate, using Javascript script, HTML document that collects the user
input (the valid format is: A digit from 1 to 4 followed by two upper-case characters followed
by two digits followed by two upper-case characters followed by three digits; no embedded
spaces allowed) of the user. Event handler must be included for the form element that collects
this information to validate the input. Messages in the alert windows must be produced when
errors are detected.
Solution:
56
Activity 2:
Using REGEX to perform character recognition in a string. Also use global(g) case sensitive(i) and
multiline(m) search.
Solution:
Activity 3:
Validate email field while creating a signup form. Also show the error messages if email is not valid.
Use event handler for input field to validate email.
Solution:
57
3) Graded Lab Tasks
Note: The instructor can design graded lab activities according to the level of difficult and complexity
of the solved lab activities. The lab tasks assigned by the instructor should be evaluated in the same lab.
Lab Task 1
Validate password field while creating signup form. Ask the user to set a strong password by using at
least 1 uppercase letter, 1 lowercase letter, 1 digit and 1 ASCII character show the error messages if
password doesn’t contain any of these expressions.
58
Lab 10
PHP Basics
Objective:
To familiarize students with the basic programming constructs in PHP.
Activity Outcomes:
After this lab the students should be able to use
• PHP constructs to solve basic programming problems
Instructor Note:
As pre-lab activity, read Chapter 1 from the textbook “Beginning PHP and MySQL: From Novice to
Professional 5th ed. Edition by by Frank M. Kromann, Year 2018”
1) Useful Concepts
PHP is a powerful server side scripting language. It is used to create dynamic web pages. It is
mainly
used to manage database at server. PHP can be embedded with HTML in three ways
• We can add blocks of PHP code in HTML
• We can use HTML instructions in PHP
• We can write standalone PHP script
Following are some of the basic rules for writing PHP code
• Blocks of PHP code can be added in HTML code with opening and closing tags, as
follows:
59
We can also use echo command as
echo “Welcome to PHP”;
print command can also be used to write out put on the browser. The syntax of writing print
command is
print(“Welcome to PHP”); or print “Welcome to PHP”;
echo is marginally faster as compared to print as echo does not return any value. printf function
can also be used to output a formatted string.
We can also write HTML instructions in PHP. The echo statement outputs whatever it’s told to
the browser. It can output not only plain text but also HTML tags. We have to write HTML tags
in quotation marks. In PHP single and double quotation marks are used interchangeably but their
logical sequence is must to maintain.
A constant is a placeholder for a value that you reference within your code that is formally
defined before using it. The name of a constant in PHP begins with a letter or an underscore.
Names of constants are case sensitive. Typically they are named using all capital letters. PHP
function define() is used to assign a value to a constant.
In PHP, variable names begin with $ sign. First character must be a letter or underscore while
remaining characters may be letters, numbers or underscores. Variable names are case sensitive.
We don’t need to declare or initialize variables. PHP is a loosely typed language it means that
data types does not require to be declare explicitly.
Assignment operator: = (assignment), += (Operator adds and assigns a value. For example $a +=
$b, here += adds the value of $b in $a and then assigns the result to $a. -=, *= and/= operators
can also be used), .= operator concatenates and assign the value. For example $.=$b, here .=
concatenates the value of $b with $a and then assigns this value to $a)
String operators: . (Concatenate two strings), .= (concatenates; and assign the value).
Increment and decrement operators: ++ (increment), -- (decrement). These operators can be used
either in prefix or postfix form.
Logical operators: AND or && (logical and), OR or || (logical or), Not or! (logical not) and XOR
(logical exclusive-or).
Comparison operators: = = (equality), = = = (checks both types and values of variables), !=
(inequality), > (greater), < (less), >= (greater or equal) and <= (less or equal).
Conditional statements: Conditional statements make it possible for your computer program to
respond accordingly to a wide variety of inputs, using logic to discern between various
conditions based on input value. In PHP following conditional statements are available.
60
If statement: if statements allow code to be executed when the condition specified is met; if the
condition is true then the code in the curly braces is executed. Here is the syntax for an if
statement:
if (condition)
{ statement }
if….else statement: When you have two possible situations and you want to react differently for
each, you can use an if...else statement. This means: “If the conditions specified are met, run the
first block of code; otherwise run the second block.” The syntax is as follows:
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is false
}
Switch statement: You can think of the switch statement as a variant of the if-else combination,
often used when you need to compare a variable against a limited number of values called cases
in switch statement terminology. The syntax of the switch statement in PHP is
switch(variable)
{
case option:
action break;
.
.
}
Looping statements in PHP: Looping statements are used to execute the same block of code a
specified number of times. Following are the basic loops in PHP.
A while loop runs the same block of code while or until a condition is true. Syntax of for loop is
given below
while loop:
while(condition)
{
Statements Increment/decrement
}
A do while loop runs once before the condition is checked. If the condition is true, it will
continue to run until the condition is false. (The difference between a do and a do while loop is
that do while runs once whether or not the condition is met.).
do
{
61
Statements Increment/decrement
}
while(condition)
A for loop runs the same block of code a specified number of times (for example, five times).
for (init counter; test counter; increment counter) { code to be executed;
}
A foreach loop is used to read an array.
foreach (array_expression as $value)
{ statement}
Arrays in PHP: An array is traditionally defined as a group of items that share certain
characteristics. Each item consists of two components; the key and a value. Key is the index of
the item in the array and value is the value of the item. PHP doesn’t require that you assign a size
or type to an array at creation time.
Declaring an array: PHP doesn’t even require that you declare the array before using it, although
you’re free to do so. We just add items to the array. We can add an item to a list as
$array-name[index of the element]= value;
For example we can start and add an item in an array as given below
$players[0] = ‘Muhammad Yousuf’;
We can add more items in the similar way but use a different index
$players[1]=”Ricky Ponting”;
Accessing an array: we can read an array item just by entering the array name and the index of
the item. For example if we want to read and display the value of second item in the $players
array we can do this as given below
echo $players[1];
Associative array: PHP allow us to create arrays where items are declared by name instead of
index or key number. Such an array is called an associative array. An item in an associative array
can be added as
$array-name[item name] = value For example
$players[‘yousuf’]=”Muhammad Yousuf”;
Items in associate array are accessed by name. For example, we can read the value of the above
array as
echo $players[‘yousuf’];
array() function: we can also use array function to create an array. By using this function we can
add multiple items in one line. The syntax of the array function is
$array_name=array(item_1,item_2,…item_n);
Example is $players=array(“[Link]”,”Imran Khan”);
We can also use array function to create associative arrays such as
$players=array(“Yousuf”=>“[Link]”,”imran”=>”Imran Khan”);
62
Sorting an array: PHP provides us sort() to sort an array in ascending order while rsort() function
to sort an array in descending order.
A function is a block of statements that can be used repeatedly in a program. In PHP, a function
can be defined as;
function functionName(list of arguments) { code to be executed;
}
To call the function, just write its name along with the required arguments.
Activity 1:
Solution:
<?php
echo "<table border=1 >
<tr> <th><font color=blue>Subject</th> <th>Total Marks</th><th>Obtained
Marks</font></td></tr>
<tr> <td>Web Engineering</td> <td>100</td><td>80</td></tr>
<tr> <td>Database Systems</td> <td>100</td> <td>90</td></tr>
</table>";
?>
Activity 2:
Write a PHP script to calculate and display the sum, average, and five lowest and highest numbers
from the given list.
123, 160, 62, 153, 345, 128, 387, 825, 666, 614, 723, 163, 811, 176, 732, 628, 722, 733, 755, 765,
63
794, 613, 627
Solution:
<?php
$nums = "123, 160, 62, 153, 345, 128, 387, 825, 666, 614, 723, 163,
811, 176, 732,628, 722, 733, 755, 765, 794, 613,
627";
$nums_array = explode(',', $nums);
$tot_num = 0;
$nums_array_length =
count($nums_array);
foreach($nums_array as
$num)
{
$tot_num += $num;
}
echo "Sum of Number is : ".$tot_num."
<br>";
$avg_num =
$tot_num/$nums_array_len
gth; echo "Average Number
is : ".$avg_num."
<br>";
sort($nums
_array);
echo "
List of Five Lowest
Numbers : <br>"; for
($i=0; $i< 5; $i++)
{
echo $nums_array[$i].", ";
}
echo "<br>
List of Five Highest Numbers : <br>";
for ($i=($nums_array_length-5); $i< ($nums_array_length); $i++)
{
echo $nums_array[$i].", ";
}
?>
64
Activity 3:
Write a PHP script to create the following table (using looping statement).
1+1=2 1+2=3 1+3=4 1+4=5 1+5=6
2+1=3 2+2=4 2+3=5 2+4=6 2+5=7
3+1=4 3+2=5 3+3=6 3+4=7 3+5=8
4+1=5 4+2=6 4+3=7 4+4=8 4+5=9
5+1=6 5+2=7 5+3=8 5+4=9 5+5=10
6+1=7 6+2=8 6+3=9 6+4=10 6+5=11
7+1=8 7+2=9 7+3=10 7+4=11 7+5=12
8+1=9 8+2=10 8+3=11 8+4=12 8+5=13
9+1=10 9+2=11 9+3=12 9+4=13 9+5=14
10+1=11 10+2=12 10+3=13 10+4=14 10+5=15
Solution:
65
Activity 4:
Write a PHP function that gets a number as an argument and calculates and displays its factorial.
Solution:
<?php
function findFact($n)
{
if($n<0)
echo "Please enter a positive number";
elseif($n ==0)
{
return 1;
}
else
{
return $n * findFact($n-1);
}
}
$num=6;
echo "Factorial of $num is: ".$factorial=findFact($num);
?>
Output:
Note: The instructor can design graded lab activities according to the level of difficult and complexity
of the solved lab activities. The lab tasks assigned by the instructor should be evaluated in the same lab.
Lab Tasks
1. Write a PHP program that finds the sum of all prime numbers from an array.
2. Write a nested for loop in the PHHP that prints the following output:
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
66
Lab 11
Laravel Setup and Basics
Objective:
To familiarize the students with the use of Laravel Framework.
Activity Outcomes:
After this lab, the students should be able to
Instructor Note:
As pre-lab activity, read Chapter 1, 2 from the textbook “Laravel Up and Running, A Framework
for Building Modern PHP Apps, 2nd Edition, Matt. Stauffer, Oreilly. Year 2019”
1) Useful Concepts
Laravel 4.3 was scheduled to release in November 2014, but as development progressed, it became clear
that the significance of its changes merited a major release, and Laravel 5 was released in February 2015.
Laravel 5 introduced a revamped directory structure, removal of the form and HTML helpers, the
introduction of the Contract interfaces, a spate of new views, Socialite for social media authentication,
Elixir for asset compilation, Scheduler to simplify cron, dotenv for simplified environment management,
Form Requests, and a brand new CLI.
Features
The following are some key features of the Laravel Framework:
• Bundles provide a modular. packaging system since the release of Laravel 3, with bundled
features already available for easy addition to applications. Furthermore, Laravel 4 uses Composer as a
dependency manager to add framework-agnostic and Laravel-specific PHP packages available from the
Packagist repository.
• Eloquent ORM (object-relational mapping) is an advanced PHP implementation of the active
record pattern, providing at the same time internal methods for enforcing constraints on the relationships
between database objects. Following the active record pattern, Eloquent ORM presents database tables as
classes, with their object instances tied to single table rows.
• Query builder, available since Laravel 3, provides a more direct database access alternative to the
Eloquent ORM. Instead of requiring SQL queries to be written directly, Laravel's query builder provides a
67
set of classes and methods capable of building queries programmatically. It also allows selectable caching
of the results of executed queries.
• Application logic is an integral part of developed applications, implemented either by using
controllers or as part of the route declarations. The syntax used to define application logic is similar to the
one used by Sinatra framework.
• Blade templating engine combines one or more templates with a data model to produce resulting
views, doing that by transpiling the templates into cached PHP code for improved performance. Blade
also provides a set of its own control structures such as conditional statements and loops, which are
internally mapped to their PHP counterparts. Furthermore, Laravel services may be called from Blade
templates, and the templating engine itself can be extended with custom directives.
Activity 1:
Install the Laravel Framework on your system. It will include following steps,
• Installing Composer
• Verify Compose Installation.
• Install Laravel.
• Verify Laravel Installation.
Solution:
Composer
Whatever machine you are developing on will need to have Composer installed globally. If you are not
familiar with Composer, it is the foundation of most modern PHP development. Composer is a
dependency manager for PHP, much like NPM for Node or Ruby Gems for Ruby. You will need
Composer to install Laravel, update Laravel, and bring in external dependencies. Download the latest
version of Compose installable archive file from [Link]
Windows Installer
Download and run [Link] - it will install the latest composer version whenever it is
executed.
The installer - which requires that you have PHP already installed - will download Composer for you and
set up your PATH environment variable so you can simply call composer from any directory.
68
The Laravel Installer
To install the Laravel as a global Composer dependency, type the following command in the command
prompt:
Composer global require Laravel/installer
It will install Laravel Framework in your system. The screenshot below also describes the procedure.
To verify installation of the Laravel framework on your system, type following command in the command
prompt.
69
laravel -V
Activity 2:
Creating your first project with the Laravel Framework. It will include,
Solution:
Once you have the Laravel installer tool installed, spinning up a new Laravel project is simple. Just run
the command laravel new <ProjectName> from your command line.
This will create a new subdirectory of your current directory named <ProjectName> and install a bare
Laravel project in it.
The following screenshot creates a new project with the name studentsrecords
70
The directory structure of the ‘studentsrecords’ project can be seen in the screenshot provided below:
To view the website in the browser, we can use artisan. Artisan is the command line interface included
with Laravel. Artisan exists at the root of your application as the artisan and provides a number of
71
helpful commands that can assist you while you build your application. To view a list of all available
artisan commands, you may use the list command:
php artisan list
To preview the project, we can use the following command in the command prompt.
The screenshot below shows after we run the command. It starts Laravel development server at
[Link]
Opening the URL [Link] in the browser will generate the following default landing page
of the Laravel Project.
72
Activity 3:
Creating routes and views in your project with the Laravel Framework. It will include,
Solution:
Routes:
The essential function of any web application framework is taking requests from a user and delivering
responses, usually via HTTP(S). This means defining an application’s routes is the first and most
important concept to approach when learning a web framework; without routes, you have no ability to
interact with the end user.
In Laravel application, web routes are defined in routes/[Link]. The simplest way to define a route is
to match a path (for example, /) with a closure, as described in following example,
We have now defined that, if anyone visits / (the root of your domain), Laravel’s router should run the
Closure defined there and return the result. Note that we return our content and don’t echo or print it.
Many simple websites could be defined within the web routes file. With a few simple GET routes
combined with some templates, we can serve a classic website easily.
73
Defining Routes in project ‘studentrecords’
For defining a new route /students in addition to the existing route (/), open the file
routes/[Link] and add following statement at the end of the file:
Route::get('/students', function () {
return view('students');
});
74
Views:
Views (or Templates) are files that describe how some particular output should look like. You might
have views for JSON or XML or emails, but the most common views in a web framework output
HTML.
In Laravel, there are two formats of view you can use out of the box: Blade or PHP. The difference is in
the filename: [Link] will be rendered with the PHP engine, and [Link] will be rendered
with the Blade engine.
75
Defining Views in project ‘studentrecords’
Visit URL [Link] ,it will open the following Web Page.
Controllers:
In the MVC framework, the letter ‘C’ stands for Controller. It acts as a directing traffic between Views
and Models.
Instead of defining all of your request handling logic as closures in your route files, you may wish to
organize this behavior using "controller" classes. Controllers can group related request
handling logic into a single class. For example, a Usercontroller class might handle all
incoming requests related to users, including showing, creating, updating, and deleting users.
By default, controllers are stored in the app/HTTP/Controllers directory.
Creating a Controller
Open the command prompt or terminal based on the operating system you are using and type the
following command to create controller using the Artisan CLI (Command Line Interface).
76
Replace the <controller-name> with the name of your controller. The created constructor can be seen at
app/Http/Controllers.
A basic controller code-snippet will look something like this, and you have to create in the directory
like app/Http/Controller/[Link]:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
//
The controller that you have created can be invoked from within the [Link] file using this syntax
below-
Route::get('base URI','controller@method');
77
Add following PHP function in the class [Link]
public function index () { return
view('students');
}
To invoke controller from the routes file, add the following statement in routes/[Link]
file.
Route::get('/students', 'App\Http\Controllers\StudentController@index');
Open the URL [Link] it will display the following Web Page.
78
3) Graded Lab Tasks
Note: The instructor can design graded lab activities according to the level of difficult and complexity
of the solved lab activities. The lab tasks assigned by the instructor should be evaluated in the same lab.
Lab Task 1
Modify the activities completed during the lab to create a static HTML view which returns the following
Web Page.
Lab Task 2
Define routes and views for the following Web pages of a company using Laravel Framework.
Home, Profile, Clients, Products, Contact Us.
79
Lab 12
Laravel Blade Templating
Objective:
To familiarize the students with the use of Blade Templating in the Laravel Framework.
Activity Outcomes:
After this lab, the students should be able to use
• Blade template in Laravel for creating different views in the Web Application.
Instructor Note:
As pre-lab activity, read Chapter 4 from the textbook “Laravel Up and Running, A Framework
for Building Modern PHP Apps, 2nd Edition, Matt. Stauffer, Oreilly. Year 2019”
1) Useful Concepts
Laravel 5.1 introduces the concept of using Blade, a templating engine to design a unique layout. The
layout thus designed can be used by other views and includes a consistent design and structure.
Blade is the simple, yet powerful templating engine that is included with Laravel. Unlike some PHP
templating engines, Blade does not restrict you from using plain PHP code in your templates. In fact, all
Blade templates are compiled into plain PHP code and cached until they are modified, meaning Blade
adds essentially zero overhead to your application. Blade template files use the .[Link] file extension
and are typically stored in the resources/views directory.
The complete directory structure of Laravel Blade templates is shown in the screenshot given here.
80
You can observe that all views are stored in the resources/views directory and the default view
for Laravel framework is [Link].
Blade views may be returned from routes or controller using the global view helper. Data may be
passed to the Blade view using the view helper's second argument:
Route::get('/', function () {
});
81
Activity 1:
In first activity of this lab, we will learn how to display data in blade template of Laravel Framework.
You may display data that is passed to your Blade views by wrapping the variable in curly braces. For
example, given the following students route in the project studentrecords:
Solution:
Route::get('/students', function () {
return view('students', ['name' => 'Muhammad Ali']);
});
<tr><td>{{$name}}</td></tr>
82
You are not limited to displaying the contents of the variables passed to the view. You may also echo
the results of any PHP function. In fact, you can put any PHP code you wish inside of a Blade echo
statement:
83
Activity 2:
In this activity, we will understand the implementation of blade directives in views.
Solution:
Using Blade Directives in Views:
In addition to displaying data, Blade also provides convenient shortcuts for common PHP control
structures, such as conditional statements and loops. These shortcuts provide a very clear, concise way
of working with PHP control structures while also remaining familiar to their PHP counterparts.
If Statements
Switch Statements
@switch($i)
@case(1)
First case...
84
@break
@case(2)
Second case...
@break
@default
Default case...
@endswitch
Loops
In addition to conditional statements, Blade provides simple directives for working with PHP's loop
structures. Again, each of these directives functions identically to their PHP counterparts:
@endwhile
85
Comments
In the project ‘studentprojects’, we will use loop blade directive to display information about the
students. For example, if we pass $students array described below having different attributes of the
individual students.
Place the following code snippet in the routes/[Link] file which is then handled by the view
‘students’ to display data on the Web Page for the user.
Route::get('/students', function () {
$students=[
['name'=>'Muhammad Ali', 'Email'=>'ali@[Link]', 'CNIC' => 1234],
['name'=>'Muhammad Usman', 'Email'=>'usman@[Link]', 'CNIC' =>
1234], ['name'=>'Muhammad Arslan', 'Email'=>'arslan@[Link]',
'CNIC' => 1234]
];
return view('students', ['students' => $students]);
});
• The data passed from the route file is then received in the view. It is traversed using
@for loop directive. The code for this action is given below:
• Place the following code in the view ‘views/[Link]’. It receives the data passed by
the route file and displays it on the page inside the div tag. The screenshot for the Web page is also give
below:
</tr>
86
udents[$i]['name']}}</td>
<td bgcolor="#6699FF" width="150" align="center">{{$st
udents[$i]['Email']}}</td>
<td bgcolor="#6699FF" width="150" align="center">{{$st
udents[$i]['CNIC']}}</td>
</tr>
@endfor
</table>
Activity 3:
In this activity, we will implement the concept of template inheritance in Laravel Framework.
Solution:
Template Inheritance
Blade provides a structure for inheritance that allows views to extend, modify, and include other views.
To get started, let's take a look at a simple example. First, we will examine a page layout. Since most
web applications maintain the same general layout across various pages, it's convenient to define this
layout as a single Blade view:
87
!-- resources/views/layouts/[Link] -->
<html>
<head>
</head>
<body>
<div class="container">
@yield('content')
</div>
</body>
</html>
As you can see, this file contains typical HTML mark-up. However, take note of the @yield directives.
The @yield directive is used to display the contents of a given section.
Now that we have defined a layout for our application, let's define a child page that inherits the layout.
Extending A Layout
When defining a child view, use the @extends Blade directive to specify which layout the child view
should "inherit". Views which extend a Blade layout may inject content into the layout's sections using
@section directives. Remember, as seen in the example above, the contents of these sections will be
displayed in the layout using @yield:
88
The @yield directive also accepts a default value as its second parameter. This value will be rendered if
the section being yielded is undefined:
In project ‘studentrecords’, currently we have got following two views corresponding to two different
routes:
• [Link]
• [Link]
If we look at the code of these template files, they both have the same header and footer parts. It would
be better if we can create a generic parent layout which consists of header and footer parts. This generic
layout can then be used in both the child layouts using the concept of template inheritance. It will avoid
the repetition of code and will help in easily maintaining the code for layouts. The following steps are
followed for template inheritance in project ‘studentsrecords’:
1. Create a new parent template named, [Link] and place header and footer parts of
the layout in that file.
89
3. Add a @yield directive in the parent template [Link] to display the contents of a
given section.
4. Preview of the Web page in the Web browser should look like this:
90
3) Graded Lab Tasks
Note: The instructor can design graded lab activities according to the level of difficult and complexity
of the solved lab activities. The lab tasks assigned by the instructor should be evaluated in the same lab.
Lab Task 1
Extend the work completed in the Lab to add both internal and external CSS styles in the ongoing project
‘studentsproject’.
Lab Task 2
Create layouts for company Web application with following pages using Blade template language of the
Laravel Framework.
1. Home
2. Profile
3. Clients
4. Products
5. Contact Us
91
Lab 13
Laravel and MySQL
Objective:
To familiarize students with the following concepts using Laravel Framework:
• Database Connectivity.
• Data Insertion.
• File Uploading.
• Data Retrieval.
Activity Outcomes:
After this lab, the students should be able to
• store and retrieve information from MySQLdatabase using Laravel Framework.
Instructor Note:
As pre-lab activity, read Chapter 5 from the textbook “Laravel Up and Running, A Framework
for Building Modern PHP Apps, 2nd Edition, Matt. Stauffer, Oreilly. Year 2019”
1) Useful Concepts
Almost every modern web application interacts with a database. Laravel makes interacting with databases
extremely simple across a variety of supported databases using raw SQL, a fluent query builder, and the
Eloquent ORM. Currently, Laravel provides first-party support for four databases:
• MySQL 5.6+ (Version Policy)
• PostgreSQL 9.4+ (Version Policy)
• SQLite 3.8.8+
• SQL Server 2017+ (Version Policy)
Database Connection
In a fresh Laravel installation, the root directory of your application will contain a .[Link] file that
defines many common environment variables. During the Laravel
installation process, this file will automatically be copied to .env.
Laravel's default .env file contains some common configuration values that may differ based
on whether your application is running locally or on a production web server. These values are
then retrieved from various Laravel configuration files within the config directory using
Laravel's env function.
92
Mention the name of the already created MySQL database as the value of the DB_DATABASE variable.
In the screenshot below, we have specified ‘testdb’ as the value of the environment variable.
Once you have configured your database connection, you may run queries using the DB facade.
The DB facade provides methods for each type of query: select, update, insert, delete, and statement.
Running a Select Query
To run a basic SELECT query, you may use the select method on the DB facade:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
/**
* @return \Illuminate\Http\Response
*/
93
{
The first argument passed to the Select method is the SQL query, while the second argument
is any parameter bindings that need to be bound to the query. Typically, these are the values of the where
clause constraints. Parameter binding provides protection against SQL injection.
The Select method will always return an array of results. Each result within the array will
be a PHP stdClass object representing a record from the database:
Instead of using ? to represent your parameter bindings, you may execute a query using named bindings :
To execute an insert statement, you may use the insert method on the DB facade.
Like select, this method accepts the SQL query as its first argument and bindings as its second argument:
94
File uploading using Laravel:
Sometimes, we have to get input from a user in form of a file. Usually, the attached file is handled in two
ways:
1. uploading the file to the server while storing its reference in the database and
2. Saving the file in the database.
In this lab, we are going to follow first approach for uploading the file. To upload the file to the server we
use the following function:
bool move (string $destination, string $filename)
$pic = $request->file('pic');
$picName = $pic->getClientOriginalName();
$pic->move('uploads',$picName);
Activity 1:
Suppose the students uses the following form to get registered with your website. Create a view having
a Web Form which collects information from the user and adds that information in the MySQL
database ‘testdb’ using the Laravel Framework.
In the database “testdb”, create a table “users” with columns names user_Id, user_Name, user_Email,
user_CNIC, user_Comments and user_Picture. Write a PHP code that:
95
Solution:
Step 1:
Step 2:
Step 2:
Define Coloumns :
Laravel Step 1
Step 1:
Create a new template with the title ‘[Link]’. Write the following code in the
‘view/students/[Link]’ file.
External CSS
@extends('[Link]')
@section('content')
96
<form action="/students/create" method="POST" enctype="multipart/form-
data">
@csrf
<table width="450px" border="0" bgcolor="#6699FF" align="center">
<tr>
<th valign="top" colspan="2" bgcolor="#666699"> User Registration Form
</th>
</tr>
<tr>
<td valign="top">
<label for="first_name">First Name *</label>
</td>
<td valign="top">
<input type="text" name="first_name" maxlength="50" size="30">
</td>
</tr>
<tr>
<td valign="top"">
<label for="last_name">Last Name *</label>
</td>
<td valign="top">
<input type="text" name="last_name" maxlength="50" size="30">
</td>
</tr>
<tr>
<td valign="top">
<label for="email">Email Address *</label>
</td>
<td valign="top">
<input type="text" name="email" maxlength="80" size="30">
</td>
</tr>
<tr>
<td valign="top">
<label for="first_name">CNIC No. *</label>
</td>
<td valign="top">
<input type="text" name="cnic" maxlength="50" size="30">
</td>
</tr>
<tr>
<td valign="top">
<label for="telephone">Telephone Number</label>
</td>
<td valign="top">
<input type="text" name="telephone" maxlength="30" size="30">
</td>
</tr>
<tr>
<td valign="top">
<label for="telephone">Your Picture</label>
</td>
<td valign="top">
<input type="file" name="pic" maxlength="30" size="30">
</td></tr>
<tr>
97
<td valign="top">
<label for="comments">Comments on Your Self *</label>
</td>
<td valign="top">
<textarea name="comments" maxlength="1000" cols="25" rows="6"></textarea>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:center">
<input type="submit" value="Submit">
</td>
</tr>
</table>
</form>
@endsection
Step 2:
Define the following route in the file ‘routes/[Link]’
Route::post('/students/create', 'App\Http\Controllers\StudentController@store');
Step 3:
Step 4:
[Link]
98
body {
background-color: lightblue;
}
h1 {
color: navy; margin-left: 20px; font-family: verdana;
font-size: 50px;
}
#para1 {
text-align: center; color: red;
}
.center {
text-align: center; color: yellow;
}
<html>
<head>
<title>Using divs</title>
</head>
<body>
<div>
<div style="width:100px;backround-color:gray">First</div>
<div style="width:100px;backround-color:red">second</div>
</div>
</body> </html>
Activity 2:
Create a new view that retrieves information from the MySQL database and displays that
information on the Web Page.
Solution:
Step 1:
99
Step 2:
Write the following PHP function in the file
‘app/Http/Controllers/[Link]’
Step 3:
Create a new template with the title ‘[Link]’. Write the following code in the
‘view/students/[Link]’ file.
@extends('[Link]')
@section('content')
<table border="1" align="center">
<tr>
<th bgcolor="#666699">Name</td>
<th bgcolor="#666699">Email</td>
<th bgcolor="#666699">CNIC</td>
<th bgcolor="#666699">Comments</td>
<th bgcolor="#666699">Telephone</td>
<th bgcolor="#666699">Photo</td>
<th bgcolor="#666699">Delete</td>
<th bgcolor="#666699">Edit</td>
</tr>
@foreach ($students as $student)
<tr>
<td bgcolor="#6699FF" width="150" align="center">{{ $student->user_Name
}}</td>
<td bgcolor="#6699FF" width="200" align="center">{{ $student->user_Email
}}</td>
<td bgcolor="#6699FF" width="200" align="center">{{ $student->user_CNIC
}}</td>
<td bgcolor="#6699FF" width="300" align="center">{{ $student-
>user_Comments }}</td>
<td bgcolor="#6699FF" width="100" align="center">{{ $student-
>user_Telephone }}</td>
<td bgcolor="#6699FF" width="100" align="center"><img src = {{ $student-
>user_Picture }}></td>
<td bgcolor="#6699FF" width="100" align="center">
<a href="delete/{{ $student->user_id }}" onclick="return confirm('Do you
really want to delete this record?')">DELETE</a></td>
<td bgcolor="#6699FF" width="100" align="center">
<a href="update/{{ $student->user_id }}" onclick="return confirm('Do you
really want to update this record?')">EDIT</a></td>
</tr>
@endforeach
</table>
@endsection
100
Step 4:
Opening the following URL [Link] will display the Web Page
carrying information about all the student records.
Lab Task 1
Create the following form with the search field. Write a PHP script that searches and displays users
with the same email address as entered by the user.
Lab Task 2
Create Web Forms for the following Web Pages for collecting user information using the Laravel
Framework.
1. Profile
2. Contact Us
101
Lab 14
CRUD Operations
Objective:
To familiarize students with the update and delete CRUD Operations in MySQL using Laravel
Framework.
Activity Outcomes:
After this lab, the students should be able to
• Insert, retrieve, delete and update records in MySQL using Laravel Framework.
Instructor Note:
As pre-lab activity, read Chapter 5 from the textbook “Laravel Up and Running, A Framework
for Building Modern PHP Apps, 2nd Edition, Matt. Stauffer, Oreilly. Year 2019”
1) Useful Concepts
The update method should be used to update existing records in the database. The number of rows
affected by the statement is returned by the method:
use Illuminate\Support\Facades\DB;
$affected = DB::update('update users set votes = 100 where name = ?', ['Anita']);
The delete method should be used to delete records from the database. Like update, the number of
rows affected will be returned by the method:
use Illuminate\Support\Facades\DB;
$deleted = DB::delete('delete from users');
102
Activity 1:
• Write the code that retrieves all of the records added in the table users in the testdb database.
Add another column in each row that displays the delete option to the users (as shown in the
following Figure). When the user clicks on the delete link a confirm box should open and after
confirmation that row should have been deleted from the table.
Solution:
Step 1:
Create a new template with the title ‘[Link]’. Write the following code in the
‘view/students/[Link]’ file.
@extends('[Link]')
@section('content')
<table border="1" align="center">
<tr>
<th bgcolor="#666699">Name</td>
<th bgcolor="#666699">Email</td>
<th bgcolor="#666699">CNIC</td>
<th bgcolor="#666699">Comments</td>
<th bgcolor="#666699">Telephone</td>
<th bgcolor="#666699">Photo</td>
<th bgcolor="#666699">Delete</td>
<th bgcolor="#666699">Edit</td>
</tr>
@foreach ($students as $student)
<tr>
<td bgcolor="#6699FF" width="150" align="center">{{ $student->user_Name
}}</td>
<td bgcolor="#6699FF" width="200" align="center">{{ $student->user_Email
}}</td>
<td bgcolor="#6699FF" width="200" align="center">{{ $student->user_CNIC
}}</td>
<td bgcolor="#6699FF" width="300" align="center">{{ $student-
>user_Comments }}</td>
<td bgcolor="#6699FF" width="100" align="center">{{ $student-
>user_Telephone }}</td>
<td bgcolor="#6699FF" width="100" align="center"><img src = {{ $student-
>user_Picture }}></td>
<td bgcolor="#6699FF" width="100" align="center">
<a href="delete/{{ $student->user_id }}" onclick="return confirm('Do you
really want to delete this record?')">DELETE</a></td>
103
<td bgcolor="#6699FF" width="100" align="center">
<a href="update/{{ $student->user_id }}" onclick="return confirm('Do you
really want to update this record?')">EDIT</a></td>
</tr>
@endforeach
</table>
@endsection
Step 2:
Define the following route in the file ‘routes/[Link]’ for the user click at delete link within
the data table.
Route::get('delete/{id}','App\Http\Controllers\StudentController@destroy');
Step 3:
Step 4:
Open the following URL: [Link] Click on the corresponding
DELETE link of the row to delete the record. The following confirm dialog box will be displayed.
Step 5:
When the user clicks on the OK button, the record will be deleted from the database and the updated
Web Page will be displayed to the user.
104
Activity 2:
When the user clicks on the EDIT link, another form displaying the existing record should open.
When user submits this form after updating the values; the new values should replace the existing
ones in the database.
Solution:
Step 1:
When the user clicks on the Update link in the [Link] (See Step 1 of Activity 1), the
following route should be activated.
Route::get('update/{id}', 'App\Http\Controllers\StudentController@update');
Step 2:
Step 3:
Create a new template with the title ‘[Link]’. Write the following code in the
‘view/students/[Link]’ file.
@extends('[Link]')
@section('content')
<form action="/students/update/{{ $users[0]->user_id }}" method="POST"
enctype="multipart/form-data">
@csrf
<table width="450px" border="0" bgcolor="#6699FF" align="center">
<tr>
<th valign="top" colspan="2" bgcolor="#666699">
User Registration Form
</th>
</tr>
<tr>
<td valign="top">
<label for="first_name">First Name *</label>
</td>
<td valign="top">
<input type="text" name="first_name" maxlength="50" size="30" value = {{
$users[0]->user_Name }}>
105
</td>
</tr>
<tr>
<td valign="top"">
<label for="last_name">Last Name *</label>
</td>
<td valign="top">
<input type="text" name="last_name" maxlength="50" size="30" value ={{
$users[0]->user_Name }}>
</td>
</tr>
<tr>
<td valign="top">
<label for="email">Email Address *</label>
</td>
<td valign="top">
<input type="text" name="email" maxlength="80" size="30" value ={{
$users[0]->user_Email }}>
</td>
</tr>
<tr>
<td valign="top">
<label for="first_name">CNIC No. *</label>
</td>
<td valign="top">
<input type="text" name="cnic" maxlength="50" size="30" value ={{
$users[0]->user_CNIC}}>
</td>
</tr>
<tr>
<td valign="top">
<label for="telephone">Telephone Number</label>
</td>
<td valign="top">
<input type="text" name="telephone" maxlength="30" size="30" value ={{
$users[0]->user_Telephone}}>
</td>
</tr>
<tr>
<td valign="top">
<label for="telephone">Your Picture</label>
</td>
<td valign="top">
<input type="file" name="pic" maxlength="30" size="30">
</td>
</tr>
<tr>
<td valign="top">
<label for="comments">Comments on Your Self *</label>
</td>
<td valign="top">
<textarea name="comments" maxlength="1000" cols="25" rows="6">{{ $users[0]-
>user_Comments }}</textarea>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:center">
106
<input type="submit" value="Update">
</td>
</tr>
</table>
</form>
@endsection
Step 4:
Route::post('/students/update/{id}','App\Http\Controllers\StudentController@displ
ay');
Step 5:
Open the following URL: [Link]
107
Step 6:
1. The code for the view [Link] is provided in the Step 3, which will receive
the data and display it in the Web Form using Blade directives. Note that all the input fields
in the form are filled by retrieving data from the database.
Step 7:
Note: The instructor can design graded lab activities according to the level of difficult and complexity
of the solved lab activities. The lab tasks assigned by the instructor should be evaluated in the same lab.
Lab Task 1
Add features for updating and deleting the records of company employees using Laravel Framework.
1. Home
2. Profile
3. Clients
4. Products
5. Contact Us
108