0% found this document useful (0 votes)
32 views9 pages

Topic 8

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views9 pages

Topic 8

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Topic 8.

CRUD Operations
Introduction

CRUD (create, read, update, delete) is an acronym for the ways in which stored information
can be operated on. It is a term for the four functions of persistent storage. CRUD usually refers
to operations performed on a database or data store but can be applied to higher level functions
such as soft deletes, where information is not necessarily deleted, but marked as deleted
through a status (MDN, 2022).

During this topic you will explore the ways in which Laravel can work with these operations,
but before you begin, you will start a new Laravel application, set up the database, and explore
a problem in which you will model and create its models, controllers, and migrations.

To create a new Laravel application as practice, perform the following steps:

Laravel activity
Explanation

8.1. Read and delete

Read

We will interpret that, to read, we will get two views: index.blade.php and show.blade.php,
since index lists all the records of the students table, and show presents a particular record. Let's
start with index:

In our app/Http/controllers/StudentController.php controller we will put the following in the


index () function:

public function index()


{
$students = Student::all();

return view('student.index', compact('students'));


}

As you can see, in a variable called "students", we make use of the student model and fetch all
its records. Finally, we return the index view of the student folder (Laravel interprets directories
and files with a dot, so student.index is equivalent to student/index.blade.php. It is not
necessary to put "blade.php", when returning a view, Laravel knows that it is a file of Blade
type).
If you followed all the steps up to this point and you have your services started, you should see
the following when accessing the URL http://crud.test/student.

For the show view, you will notice that when listing the elements of the table, thanks to a
@foreatch, the object that was returned when displaying the index view (students in plural), we
create a Table Row ("<tr></tr>") and in each <a> tag in the href property we send it to the path
"student.show" with the parameter of the ID that corresponds to each student (in singular):

<td><a href="{{ route('student.show', $student->id) }}">{{ $student->id }}</a></td>


<td><a href="{{ route('student.show', $student->id) }}">{{ $student->first_name }}</a></td>
<td><a href="{{ route('student.show', $student->id) }}">{{ $student->last_name }}</a></td>

In our controller, we must add the following in the show () function:

public function show($id)


{
$student = Student::findOrFail($id);

return view('student.show', compact('student'));


}

Notice that we look up a student by its ID and store it in a student variable (singular), which we
inject into the returning view.

Delete

Although we don't have records to delete yet, we could directly inject some records manually
into the database, but we will work on its function in the controller:

In our app/Http/controllers/StudentController.php controller we will put the following in the


destroy () function:

public function destroy($id)


{
$student = Student::findOrFail($id);
$student->delete();

return redirect('/student')->with('success', 'Student data is successfully deleted');


}

Notice that we search by ID a student and store it in a variable "student", then, thanks to the
delete () method, we delete it and return with a redirect to the path /student with a message.
Notice in the index view file that by clicking on the "Delete" button, using a form, we are
sending the student's ID to the path "student.destroy":

<form action="{{ route('student.destroy', $student->id) }}" method="post">


@csrf
@method('DELETE')
<button class="btn btn-danger" type="submit">Delete</button>
</form>

8.2. Create

Within the create () function, we must add the following in our controller:

public function create()


{
return view('student.create');
}

The only thing we do is to return the create view, which is a form that, when filled, will be
processed by the store () function. Inside the store () function we will put the following:

public function store(Request $request)


{
$validatedData = $request->validate([
'first_name' => 'required|max:75',
'last_name' => 'required|max:75',
'description' => 'required',
]);
Student::create($validatedData);

return redirect('/student')->with('success', 'Student is successfully saved');


}

Validations can be done by the frontend (placing the required attribute in the input text of each
field) or by the backend through the model or the controller. In our case, we will do it through
the controller with the validate function that comes incorporated in the Request.

We store the object in a variable (which we will later use to create the record), where each
attribute will be validated. Remember to see the official documentation to determine the types
of constraints and the general use of validations in https://laravel.com/docs/7.x/validation).

If the validation passes because of the model, you will be able to create the record in the table,
passing it as parameter, the variable where we store the validated object; otherwise, it will
return to the view with content in an internal variable called "errors". Observe the following in
the create view:

@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div><br />
@endif

If there is an error of any kind, we will display an alert with html and Bootstrap, and we will
walk through the errors via a @foreatch.

Very important. As we use the model to process the information directly in the table,
Laravel protects all the Eloquent models, so we must specify the attributes that will be able
to be treated in a massive way. We do this with the protected function fillable, which,
inside of it, we will put the attributes that will be treated from our views, and validated by
the controller:

class Student extends Model


{
protected $fillable = [
'first_name', 'last_name', 'description'
];
}

Once the fillables are declared in the model, the store () function can work, redirecting to
the index view.

Make as many records as you wish for your tests.

8.3. Update

Finally, after listing all the records, viewing a particular record, creating a new one and then
deleting it, it is time to update an existing record. As you can see, in the index, there is a Table
Row containing a <a> tag that sends to a path called "student.edit" and sends the student ID as a
parameter:

<td><a href="{{ route('student.edit', $student->id) }}" class="btn btn-primary">Edit</a></td>

The function in charge of processing this request is edit () and its content is the following:
public function edit($id)
{
$student = Student::findOrFail($id);

return view('student.edit', compact('student'));


}

The function searches for the ID and returns the student.edit view with the variable where the
search result was stored.

The view displays the information in the inputs in its value property, showing the following:

When saving, the function in charge of processing the information update, the update ()
receives the ID of the student and the Request with all the information of the inputs.

A good trick to see what the request has is to use the "dd" command:

public function update(Request $request, $id)


{
dd($request->all());

This will display information in an array with a variable content according to each form
without executing the immediate lines that come in the controller. It is, in short, an alternative
method of depuration:
Now that we know what the Request has, we proceed to process that information in the
controller:

public function update(Request $request, $id)


{
$validatedData = $request->validate([
'first_name' => 'required|max:75',
'last_name' => 'required|max:75',
'description' => 'required',
]);
Student::whereId($id)->update($validatedData);

return redirect('/student')->with('success', 'Student data is successfully updated');


}

As in the store () function, we validate all the information and, if it passes, we look for the ID
to the student, and through the update () method, we inject the validation parameter where all
the information to be updated comes. We redirect to the URL /student with information.

Conclusion

In general, CRUD operations are the basis for information processing in most business
applications that require record additions, deletions, or modifications.

In the same way that we make a CRUD through the model, views, and controller in Laravel
from the controller and API routes, we can create CRUD to be used by third party applications.
This is very useful when our application will be used by other applications, for example, mobile
applications, where the backend and frontend are independent projects. The principle is the
same, only the return of the information changes; instead of returning a view, a JSON object is
returned.

Checkpoint

Make sure that you:

 Understand the concept of CRUD.


 Practice creating projects in Laravel 7.
 Understand the MVC design pattern.

References
 MDN. (2022). CRUD. Retrieved from
https://developer.mozilla.org/es/docs/Glossary/CRUD

Additional Resources

The following links do not belong to Tecmilenio University, when accessing to them, you
must accept their terms and conditions.

Videos

 To learn about CRUD operations, watch the following video:


TheCodePro. (2021, January 11). Laravel 8 CRUD Tutorial For Beginners [Video
file]. Retrieved from https://www.youtube.com/watch?v=QVNQq-LfHBk

 To learn about building CRUD, watch the following video:


Laravel. (2021, August 9). 03- Building a CRUD Application [Video file]. Retrieved
from https://www.youtube.com/watch?v=iIazajpaOSw

 To learn about MVC design pattern, watch the following video:


Web Dev Simplified. (2019, April 3). MVC Explained in 4 Minutes [Video file].
Retrieved from https://www.youtube.com/watch?v=DUg2SWWK18I

Readings

 To learn more about CRUD, we recommend reading:


MongoDB. (2022). MongoDB CRUD Operations. Retrieved
from https://www.mongodb.com/docs/manual/crud/

 To learn more about CRUD operations, we recommend reading:


Sarangam, A. (2021). CRUD Operations: A Simple Guide For 2021 In 5 Easy Points.
Retrieved from https://www.jigsawacademy.com/blogs/data-science/crud-operations/
 To learn more about MVC design pattern, we recommend reading:
Tutorialspoint. (2022). Design Patterns - MVC Pattern. Retrieved
from https://www.tutorialspoint.com/design_pattern/mvc_pattern.htm

Activity 8

Description

The student will create a CRUD in Laravel 7.

Objective

To learn how to add, change, modify or delete information in a database.

Requirements

Computer with Internet access, have XAMPP, or the WAMP, MAMP, LAMP or Laragon Stack
installed.

Instructions

You will create a system for data additions, deletions, changes, and deletions that contains the
following features:

1. A CRUD system to register superheroes containing the following fields:


o Superhero's real name.
o Name by which the superhero is known.
o Superhero's photo (it can be an external resource; in the field you will store the
URL of the superhero's photo).
o Additional information about the superhero.
2. You will create a Laravel 7 project with the name "superheroes".
3. You will create its Model, Views, Controller and Migration.
4. The system will be able to register a new superhero, edit superhero, view its full
record, or unregister the superhero.
5. You will upload the project to GitHub.

Deliverable(s)

A report document that includes all the screenshots of all the views of your project and the
URL of your project on GitHub.

Evaluation criteria:

 The project must allow the registration of a new superhero.


 The project must allow the visualization of the superhero.
 The project must allow editing the superhero.
 The project must allow deleting the superhero.
 The project must list all superheroes.
 Screenshots of the project views.
 URL of the project on GitHub.

Homework 7

Instructions

Create a personal system where you can enter the grades of your subjects. Therefore, do the
following:

1. First, create a Laravel 7 project called "grades", just like the project on GitHub.
2. Then, develop a CRUD where you list the subjects.
3. When selecting a subject, the grades for each gradable activity (homework, activity,
quick test, midterm, among others.) should be displayed.
4. Next, you must have the possibility to add a new evaluable activity, where you will
put the type of activity, grade, date and, optionally, a space for a grade.
5. Finally, the system must allow to modify activities and grades, as well as to delete
them.

Deliverable(s)

Submit your results in the corresponding space on the platform.

You might also like