Web Technologies Week 09-10 (CRUD)
Web Technologies Week 09-10 (CRUD)
Since our target software is University Learning Management System (LMS), therefore few
prominent entities include: Student, Department, Teacher, Course, Admission Office, and others.
This section would help you to implement in Laravel the Student entity. Other entities can be
implemented in the same way. Next sections would guide you how to create one-to-many (1xM)
and many-to-many (MxM) Relationships.
NOTE: The Laravel commands used below need to be typed in the Terminal Window of VS
Code which can be opened using the shortcut key Ctrl + ~ (called control console) or by clicking
the VS Code menu: Terminal > New Terminal.
To provide CRUD for an entity or relation, we first implement Create, then Read, then Update
and finally Delete operation. While implementing each operation:
- we will first work with the Model layer
- then with the View layer
- and finally, with the Controller layer
Let’s implement CRUD operation for the Student entity. Then implement CRUD for the 1xM
Department-Student relation and finally implement CRUD for MxM Course-Student join-
relation.
1
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
2
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
ii. At this time, the table, students, has NOT been created in the database.
3
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
4
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
vi. The following command reverses last N migrations. Thus, if N=3, last 3
migrations would be reversed
▪ php artisan migrate:rollback --step=N
vii. The following command drops all tables and performs migrations again
▪ php artisan migrate:fresh
viii. After the migrate command, the table, students, would have been created in
the database.
B. Write code for the create Webpage (View) and add Routes
a) Create student folder in resources > views
b) In student folder, add new file, create.blade.php
5
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
<body>
<h2 style="border: 1px solid black; background-color:DodgerBlue; text-align:center;">
Add New Student
</h2>
<!-- For Redirecting With Flashed Session Data when 'Submit' button -->
<!-- is pressed in the 'create.blade.php' view which calls the relevant -->
<!-- function 'store' in the StudentController and then this -->
<!-- view, 'create.blade.php' is again called -->
<!-- START -->
@if (session('status'))
<div class="alert alert-success alert-dismissible">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
{{ session('status') }}
</div>
@endif
<!-- END -->
6
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
d) Routes
i. For the above webpage, the following page should open in the browser if the
browser is aware of the URL which has been typed in the address bar. In our
case the browser is NOT aware. To achieve this in MVC, we need to define a
Route.
iv. The Route of a web page is written in the file resources > web.php
v. A route binds a URL with a function which is written inside Controller
vi. The function is called/executed when the URL is provided to the address bar of
browser
7
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
▪ Route::get('student/create', 'StudentController@create')-
>name('student.create');
▪ Here,
o student/create is the user-defined URL and is associated with the
create webpage of student. There can be other create webpages for
other entities as well, e.g. teacher.
o StudentController@create means call the create() function in the
StudentController
o name(‘student.create’) is a user-defined alternate name of the route
▪ Here,
o student/store is the user-defined URL and is associated with the click
action of Submit button on Student Form
o StudentController@store means call the store() function in the
StudentController
o name(‘student.store’) is a user-defined alternate name of route
8
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
c) Include Model name in the Controller. So, we add ‘Student’ model in the
‘StudentController’ controller.
▪ use App\Student;
d) The create() function is given below which is invoked when the URL is typed in
the browser. This function displays the create webpage
public function create() {
return view ("student.create");
}
e) The store() function is given below which inserts form data into the table
students
$student = new Student; // Must import the Model file: use App\Student;
$student->cnic = $request->get('cnic');
9
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
$student->name = $request->get('name');
$student->address = $request->get('address');
$student->telno = $request->get('telNo');
$student->age = $request->get('age');
// --------------------------------------
// Help on the following code is given at the following URL
// https://laravel.com/docs/5.8/redirects#redirecting-with-flashed-session-data
//
return redirect('student/create')
->with('status', 'CNIC '.$student->cnic.' added Successfully!');
// --------------------------------------
}
10
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
i. When user presses the submit button, the route student.store is searched in web.php.
When student.store route is found, the StudentController function store() is searched
and executed. The store function stores form data in the students table and then
displays the create page.
ii. Add few students so that we can view / update / delete them
B. Write code for the ‘read’ Webpage (View) and add Routes
a) In the student folder, add new file, read.blade.php
11
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
<!-- Cascading Style Sheet applied to different parts of the table -->
<!-- START -->
<style>
12
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
table, th, td {
border: 1px solid black;
text-align: center;
}
table {
margin: 25px;
}
th, td {
padding: 5px;
}
</style>
<!-- END -->
<body>
<h2 style="border: 1px solid black; background-color:DodgerBlue; text-align:center;">
View Students
</h2>
<!--
// ----------------------------------------------------------------
// *** This view would get three values from StudentController.php
// 1. a code to identify that update or delete operation was performed in controller
// 2. updated student list
// 3. CNIC of the student which has been updated/deleted
// ----------------------------------------------------------------
-->
<!-- For Redirecting With Flashed Session Data when 'Delete' or 'Update' -->
<!-- button is pressed in the 'list.blade.php' view which calls the relevant -->
<!-- function 'delete' or 'update' in the StudentController and then this -->
<!-- view, 'list.blade.php' is again called -->
<!-- START -->
@if (session('status'))
<div class="alert alert-success alert-dismissible">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
{{ session('status') }}
</div>
@endif
<!-- END -->
<table>
<thead>
<tr>
13
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
<th>CNIC</th>
<th>Name</th>
<th>Address</th>
<th>Tel. No.</th>
<th>Age</th>
<th>Marital Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<p id="forDeleteCode"></p>
<!-- Using Blade Loop. -->
@foreach ($students ?? '' as $student)
<tr>
<td>{{$student->cnic}}</td>
<td>{{$student->name}}</td>
<td>{{$student->address}}</td>
<td>{{$student->telNo}}</td>
<td>{{$student->age}}</td>
<td>{{$student->marital_status}}</td>
<!-
- Below we added onclick="return confirm ('Are you sure to delete the student {{$student-
>name}} having CNIC {{$student->cnic}}?')"-->
<!-- If user presses OK on the confirmation dialogue, the route mentioned in href --
>
<!-- will be executed. In case of pressing the Cancle button, nothing happens. -->
<a class="btn" style="border: 1px solid;" href="{{URL::to('student/delete', $student
->cnic)}}" onclick="return confirm ('Are you sure to delete the student {{$student-
>name}} having CNIC {{$student->cnic}}?')" title="Delete -> {{$student->cnic}}"> <i class="fa fa-
trash"></i></a>
</td>
</tr>
@endforeach
</tbody>
</table>
</body>
</html>
14
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
▪ Route::get('student/read', 'StudentController@read')->name('student.read');
▪ Here,
o student/read is the user-defined URL and is associated with the read
webpage of student
o StudentController@read means call the read() function in the
StudentController
o name(‘student.read’) is a user-defined alternate name of the route
15
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
16
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
B. Write code for the ‘update’ Webpage (View) and add Routes
a) In the student folder, add new file, update.blade.php
17
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
<body>
<h2 style="border: 1px solid black; background-color:DodgerBlue; text-align:center;">
Update Student Record
</h2>
18
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
▪ Route::get('student/edit/{cnic}', 'StudentController@edit')-
>name('student.edit');
▪ Here,
o student/edit/{cnic} is the user-defined URL which takes one argument
which is the cnic of the student for whom Update is initiated
o StudentController@edit means call the edit() function in the
StudentController
o name(‘student.edit’) is a user-defined alternate name of the route
b) Adding Action-based route for the Update button on the update webpage
i. On the update page, when user clicks the Update button, the record of selected
student is saved in the database.
ii. To achieve this, we add the Route::post() function in resources > web.php file.
▪ Route::post('student/update/{cnic}', 'StudentController@update')-
>name('student.update');
▪ Here,
o student/update/{cnic} is the user-defined URL which takes one
argument which is the cnic of the student for whom Update is done
o StudentController@ update means call the update() function in the
StudentController
19
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
b) The update() function is given below which is invoked when Update button on
the update webpage is clicked. This function stores the information of cnic in the
database and then reloads the read webpage with the new contents of students
table.
public function update(Request $request, $cnic) {
// you can add the chech here whether this student exists or not?
// --------------------------------------
20
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
21
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
b. When user clicks the Update button, the record is saved in the students table, the
updated contents of students table are fetched and passed to the read webpage as
shown below.
22
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
B. Write code for the ‘delete’ Webpage (View) and add Routes
a) The webpage, delete.blade.php is NOT required. We can delete an item without
creating a new page
b) The Delete button is in the Action column of read.blade.php
c) The code lines, href="{{URL::to('student/delete', $student->cnic)}}", written
in read.blade.php state that the route student/delete be invoked.
▪ Route::get('student/delete/{cnic}', 'StudentController@delete')-
>name('student.delete');
▪ Here,
o student/delete/{cnic} is the user-defined URL which takes one
argument which is the cnic of the student for whom Update is initiated
23
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
// --------------------------------------
// Help on the following code is given at the following URL
// https://laravel.com/docs/5.8/redirects#redirecting-with-flashed-session-data
//
return redirect('student/read')
->with('status', 'CNIC '.$cnic.' deleted Successfully!');
// --------------------------------------
}
24
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
b) If confirmed, the cnic is passed to the delete() function of StudentController. The cnic
record is deleted from the students table. the updated contents of students table are
fetched and passed to the read webpage as shown below.
This completes our tutorial on Entity-wise CRUD in Laravel using MVC. Once you
make files for the entity Student, copy them and re-use them with some
modification for the entities Department, Course, Teacher, Admission_Office,
etc.
***
25
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
In a one-to-many relationship, one record in a table is normally associated with one or more
records in another table.
ER Diagram:
The relation between the entities Department and Student is One-to-Many. A department can have
many students while a student has only one department. The primary key(‘id’) in the table
departments should be foreign key (‘department_id’) in the table students. This is shown in the
above ER diagram.
The above diagram speaks that foreign key needs to be added to Student entity and database level
relationships needs to be defined on both sides.
Note: Make sure you have created Department entity and written its CRUD operations.
26
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
iv. The snapshot of students table below does have department_id fields but does
not have a foreign key symbol
v. Making foreign key relationship at the database level. Add the following
lines in the up() function of CreatesStudentsTable migration
27
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
vi. After adding foreign key and the foreign key constraint, the up() function looks
as below
public function up()
{
Schema::create('students', function (Blueprint $table) {
$table->string ('cnic', 15)->primary();
$table->string('name', 35);
$table->string('address', 75);
$table->string('telNo', 15);
$table->double('age');
$table->boolean('marital_status')->default(false);
// The departments table MUST exist and MUST have ‘id’ as Primary key
$table->unsignedbiginteger('department_id');
$table->timestamps();
});
}
28
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
viii. Use the following command to perform migration so that students table can
have foreign key constraint at the database level.
▪ php artisan migrate:fresh
ix. The snapshot of students table below now has foreign key symbol which
means MySQL database will make sure the foreign key constraint.
29
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
▪ In the Student model, write the function department(). It will be read as,
one student belongsTo one department.
class Student extends Model
{
protected $primaryKey = 'cnic'; // Set as primary key
public $incrementing = false; // Non auto-incrementing
/**
* Inverse relationship: Get the Department that owns the Student.
*/
public function department()
{
return $this->belongsTo(Department::class);
}
▪ Hint: Use belongsTo in the Model whose table contains Foreign Key
30
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
B. Write code for the create Webpage (View) and add Routes
a) Add code for Department dropdown in create.blade.php
<body>
<h2 style="border: 1px solid black; background-color:DodgerBlue; text-align:center;">
Add New Student
</h2>
<!-- For Redirecting With Flashed Session Data when 'Submit' button -->
<!-- is pressed in the 'create.blade.php' view which calls the relevant -->
<!-- function 'store' in the StudentController and then this -->
31
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
32
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
c) All routes in web.php for create webpage will remain the same. No change.
Only mentioning here for the sake of completeness.
▪ Route::get('student/create}', 'StudentController@create')-
>name('student.create');
▪ Route::post('student/store}', 'StudentController@store')-
>name('student.store');
▪ use App\Department;
$student = new Student; // Must import the Model file: use App\Student;
$student->cnic = $request->get('cnic');
$student->name = $request->get('name');
$student->address = $request->get('address');
$student->telno = $request->get('telNo');
$student->age = $request->get('age');
33
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
// --------------------------------------
// Help on the following code is given at the following URL
// https://laravel.com/docs/5.8/redirects#redirecting-with-flashed-session-data
//
return redirect('student/create')
->with('status', 'CNIC '.$student->cnic.' added Successfully!');
// --------------------------------------
}
i. When user presses the submit button, the route student.store is searched in web.php.
When student.store route is found, the StudentController function store() is searched
and executed. The store function stores form data in the students table and then
displays the create page.
ii. Add few students so that we can view / update / delete them
34
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
35
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
ii. Add Department name in the each row of the table on read.blade.php
<!--
We shall only get the department id that have been inserted in
the table Student.
<td>{{$student->department_id}}</td>
a) All routes in web.php for read webpage will remain the same. No change. Only
mentioning here for the sake of completeness.
▪ Route::get('student/read}', 'StudentController@read')-
>name('student.read');
36
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
the StudentController function read() is searched and executed. The read() function
fetches data from the database and displays them as shown below.
37
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
b) No change in routes for update operation. Providing routes for the sake of
completeness.
▪ Route::get('student/edit/{cnic}', 'StudentController@edit')-
>name('student.edit');
▪ Route::post('student/update/{cnic}', 'StudentController@update')-
>name('student.update');
38
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
39
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
a. When user clicks the Update button, the record is saved in the students table, the
updated contents of students table are fetched and passed to the read webpage as
shown below.
40
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
b) If confirmed, the cnic is passed to the delete() function of StudentController. The cnic
record is deleted from the students table. the updated contents of students table are
fetched and passed to the read webpage as shown below.
41
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
You can now implement all sort of 1xM relations in Laravel. Next, we guide the implementation
of 1xM relation in Laravel
***
42
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.
Created by: Dr. Maaz Rehan - CSC336 Web Programming - COMSATS University Islamabad, Pakistan
In a many-to-many relationship, one record in a table is normally associated with more than one
records in the table and vice-versa. If two entities have MxM relationship, we break it into two
1xM relationships. A new table, called join table or pivot table, is created which connects those
two tables. The relation from table 1 and table 2 to pivot table is 1xM, so there are two 1xM
relations.
***
43
Dr. Maaz Rehan, Web Engineering, CUI Wah Cantt.