Study-Guide-6-Laravel-CRUD-p1
Study-Guide-6-Laravel-CRUD-p1
WEB SYSTEMS
AND
TECHNOLOGIES
2
Module 5: Laravel CRUD
04/15/2025 2
Model and Migration
A model is used as a way for questioning data to and from the table
within the database. Laravel gives a basic way to do that using
Eloquent ORM where each table incorporates a Model to interact with
it.
Migrations are like version control for your database, allowing your
team to define and share the application's database schema
definition. If you have ever had to tell a teammate to manually add a
column to their local database schema after pulling in your changes
from source control, you've faced the problem that database
migrations solve.
The Laravel Schema facade provides database-agnostic support for
creating and manipulating tables across all of Laravel's supported
database systems. Typically, migrations will use this facade to create
and modify database tables and columns.
04/15/2025 3
Go to phpMyAdmin
Create your database ex: Laravel_mydatabase
Open your editor and open your project
Configure “.env” file to connect your project and your database
Change DB_DATABASE=Laravel_mydatabase
Open your terminal, change the active directory to your project, and
create a model for example “student”.
type:
$ php artisan make:model student –m
-m is for migration or --migration
Check your model in your editor and go to app/Models/.
*student.php is created
Check your migrations in your editor and go to database/migrations/
*student_migrations is created
04/15/2025 4
In the create_student migrations
Add attributes to the table students that was initially created ex:
$table->string(‘fname’); …
$table->integer(‘lname’);
To know the different datatypes go to Laravel.com/docs and search
for: column types
Go to terminal and type: $php artisan migrate
Go to phpMyAdmin and check for the attributes created
If encountered error in “longtext” datatype go to
AppDevice/Provider.php
Type schema::default StringLength(100); at boot() function
Type use Illuminate\Support\Facades\Schema; on the upper part
04/15/2025 5
Route Resource and Controller
Create a controller “StudentsController”
In terminal type $ php artisan make:controller StudentsController –-
resource
--resource will automatically create functions for the resource used for
CRUD
Go to routes/web.php and type:
Route::resource(‘students’, StudentsController::class);
Go to terminal type $ php artisan route:list
It will display all methods and URI for the created route resource
04/15/2025 6
Eloquent, Showing Data with
Pagination in Laravel
We will show students in Table Form with Pagination
We will be using Eloquent: ORM (Object Relational Mapping)
Go to “StudentsController”
Add on the top: use App\Models\student;
Add data into your table:students using phpMyAdmin
Inside the index() function put the following codes:
$student = student::all();
return $student;
Wherein: student is the model and all() is a method to
retrieve all the data from the students table using the
model student
04/15/2025 7
Create a view “student.blade.php”
You may add css codes to format the style
Create HTML tags and TABLE
<table>
<tr>
<th>Student Id</th>
<th>First Name</th>
<th>Middle Name</th>
<th>Last Name</th>
<th>Action</th>
</tr>
<table>
Go back to “StudentsController”
In index(), change return $student; to
return view(‘student')->with(student',$student);
In the “student.blade.php”
04/15/2025 8
Use the @foreach directive to display all rows and columns in a table
row and table data
@foreach($student as $stud)
<tr>
<td>{{$stud>studentid}}</td>
<td>{{$stud>fname}}</td>
<td>{{$stud->middlename}}</td>
<td>{{$stud->lastname}}</td>
</tr>
@endforeach
04/15/2025 9
Pagination
Go to “StudentsController” in index(), change all() to
paginate(n)
Where n is the number of rows to be displayed per page
In the “student.blade.php” below the table write the following codes:
{{$student->links()}}
In Laravel, the links() method generates the pagination controls
(previous, next, page numbers, etc.).
Go to AppServiceProvider in boot() function and write the following
codes:
Paginator::useBootstrap();
04/15/2025 11
<form action="/student" method="POST">
@csrf
<p>This is the add Student page!</p>
Client Id: <input type="text" name=”studentid"><br>
First Name: <input type="text" name="fname"><br>
Middle Name: <input type="text" name="mname"><br>
Last Name: <input type="text" name="lname"><br>
Address: <input type="text" name="address"><br>
Contact No.: <input type="text" name="contactno"><br>
<input type="submit" value="Save">
</form>
Wherein "/student” is the URI to be used to insert data to
the database and the method is POST both can be checked in
route:list
Go to “StudentsController” in store() function,
Use the two options to insert data to our table:
04/15/2025 12
Option 1, using the save() method:
$student->clientid = $request->input('clientid');
$student->fname = $request->input('fname');
$student->mname = $request->input('mname');
$student->lname = $request->input('lname');
$student->address = $request->input('address');
$student->contactno = $request->input('contactno’);
Assigns values from an incoming HTTP request ($request) to the
respective properties of the Student model.input('field_name') fetches
data from form inputs.
$student->save();
Saves the new client record into the database.
04/15/2025 13
Option 2, using the create() method:
Student::create([
”studentid"=>$request->studentid,
"fname"=>$request->fname,
"mname"=>$request->mname,
"lname"=>$request->lname,
"address"=>$request->address,
"contactno"=>$request->contactno
]);
This line of code is a Laravel Eloquent ORM method that inserts a
new record into the database using mass assignment.
Client::create([...]): Calls the create() method on the Client model to
insert a new record.The array inside create([...]) assigns values from
the request ($request) to the corresponding database columns.
04/15/2025 14
Requirements for This to Work:
> Model Must Use fillable or guarded
> In the Student model (app/Models/Student.php), you must
define $fillable to allow mass assignment:
class Student extends Model
{
//
protected $fillable = [
”studentid",
"fname",
"mname",
"lname",
"address",
"contactno"
];
}
04/15/2025 15
Showing Individual Record
Go to student.blade.php on foreach block and add the following:
<td>
<a href=”student/{{$stud->id}}">View More</a> |
</td>
Go to “StudentsController” in show() function, add the following
code:
public function show(string $id)
{
$student = Student::find($id);
return view("showStudent")->with(”student",$student);
}
$student = Student::find($id);
Uses Student::find($id) to retrieve a single student record from the
database.
find($id) searches by primary key. If no record is found, it returns null.
04/15/2025 16
return view("showStudent")->with("student", $student);
Loads the Blade view file showStudent.blade.php.
Passes the $student object to the view using with("student",
$student).
Inside the view, you can access the student data using {{ $student-
>name }}, {{ $student->id }}, etc.
04/15/2025 17
Updating Record
First look at the route:list
After the view anchor tag add Edit Anchor Tag
<a href=”student/{{$stud->id}}/edit">Edit</a>
Go to “StudentsController” in edit() function, add the
following code:
public function edit(string $id)
{
$student = Student::find($id);
return view("editStudentForm")->with(”student",$student);
}
04/15/2025 18
Create a new view editStudentForm.blade.php
Copy the code in addStudentForm
In every input field add value="{{$student->fname}}"
Change fname into different attributes
Add new Laravel blade directive: @method('PUT’) based on
route:list
Change form action to:
<form action="/student/{{$student->id}}" method="POST">
Go to “StudentsController” in update() function, add the following
code:
public function update(Request $request, string $id)
{
$student = student::find($id);
$student->fname = $request->fname;
$student->middlename = $request->middlename;
$student->lastname = $request->lastname;
$student->save();
echo "Successfully Updated!";
}
04/15/2025 19
Deleting Record
Check the route:list
After the anchor tag of EDIT create a new <form> tag
<form action=”student/{{$stud->id}}" method="POST">
@csrf
@method("DELETE")
<input type="submit" name="submit" value="DELETE">
</form>
Go to “StudentsController” in destroy() function, add the
following code:
$student = student::destroy($id);
$student->delete();
echo "Successfully Deleted!";
Or
student::destroy($id);
echo "Successfully Deleted!";
04/15/2025 20
Adding Validation
In function store of our “StudentsController” write:
$request->validate([
”studentid"=>"required|min:4|max:20|unique:students",
"fname"=>"required|min:5|max:20",
"lastname"=>"required|min:5|max:20”
...
]);
$request->validate([...])
This method is used to validate incoming request data in Laravel. It
ensures that the submitted data meets the specified validation rules.
04/15/2025 21
In “addStudentForm.blade.php” after the </form> tag write:
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
04/15/2025 22
Manually Creating Validations
In function store() of the controller replace the validate block…
$validator=Validator::make($request->all(),
[
"studentid"=>"required|min:4|max:20|unique:students",
"fname"=>"required|min:5|max:20",
"lastname"=>"required|min:5|max:20"
]
);
if($validator->fails()){
return redirect(”student/create")
->withErrors($validator)->withInput();
}
Put on top: use Validator;
Add the ff: on every input fields: value="{{old(‘studentid')}}"
04/15/2025 23