Mada za sehemu hiiBuilding the back-end using a frameworkMada 3
- Implementing routing and handling of user requests
- Implementing interaction with databases
- Implementing authentication and authorisation
Implementing Interaction with Databases
In modern web development, a website is not useful if it cannot save or retrieve data. Whether it is a user registering an account, a student checking exam results, or a shopkeeper recording sales, this data must be stored in a database.
In this topic, you will learn how to use the Laravel framework to connect to a database, define its structure, and perform the four basic operations known as CRUD (Create, Read, Update, and Delete).
Before Laravel can store information, it must know where the database is located and how to access it.
Steps to connect:
- Create the Database: Using a tool like phpMyAdmin (available in XAMPP), create a new database (e.g.,
school_db). - Configure the .env File: Laravel stores connection details in a hidden file named
.envin your project root. You need to edit this file to tell Laravel which database to use.DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=school_db DB_USERNAME=root DB_PASSWORD= - Test the Connection: Run the command
php artisan migratein your terminal. If successful, Laravel will create default tables (likeusers) in your database.
Instead of creating tables manually in phpMyAdmin, Laravel uses Migrations. A migration is a blueprint that describes exactly what columns a table should have.
Creating a table for Students:
- Run the command to create a Model and a Migration file simultaneously:
php artisan make:model Student -m - Open the new file in
database/migrations/xxxx_xx_xx_xxxxxx_create_students_table.php. - Define the columns inside the
up()method:public function up() { Schema::create('students', function (Blueprint $table) { $table->id(); // Auto-incrementing ID $table->string('name'); // Student name $table->string('class'); // Class (e.g., Form Three) $table->string('stream'); // Stream (e.g., Science) $table->timestamps(); // Created_at & Updated_at }); } - Run
php artisan migrateto create the table in the database.
A Model is a PHP class that represents a specific table in your database. It allows you to interact with the table using simple PHP code (like Student::all()) instead of writing complex SQL queries.
Enabling Mass Assignment:
To create or update a student easily, you must tell Laravel which fields are safe to fill at once. This is done in the Model file (app/Models/Student.php) using the $fillable property.
class Student extends Model{
// Allow mass assignment for these attributes
protected $fillable = ['name', 'class', 'stream'];
}
Without defining $fillable, Laravel will block creating/updating records for security reasons.
CRUD stands for Create, Read, Update, and Delete. The textbook demonstrates a Student Management System to show these operations.
A. Setting up Routes
In routes/web.php, define the URLs for the operations:
use App\Http\Controllers\StudentController;
// Read (List all students)
Route::get('/students', [StudentController::class, 'index']);
// Create (Show form)
Route::get('/students/create', [StudentController::class, 'create']);
// Store (Save new student)
Route::post('/students', [StudentController::class, 'store']);
// Edit (Show form)
Route::get('/students/{id}/edit', [StudentController::class, 'edit']);
// Update (Save changes)
Route::put('/students/{id}', [StudentController::class, 'update']);
// Delete (Remove student)
Route::delete('/students/{id}', [StudentController::class, 'destroy']);
B. Controller Methods
In app/Http/Controllers/StudentController.php, implement the logic:
- Read (Index):
$students = Student::all(); - Create (Store):
Student::create($request->all()); - Update:
$student = Student::find($id); $student->update($request->all()); - Delete:
Student::destroy($id);
C. Creating Views
You need Blade templates (HTML files) in resources/views/students/ to display the forms and the list of students (e.g., index.blade.php, create.blade.php).
Sometimes you need to find specific data, like all "Form Three" students in the "Science" stream. Laravel provides the Query Builder to handle filtering and sorting efficiently.
Example: Searching Students
- Add a method in the Controller:
public function search(Request $request) { $class = $request->input('class'); // Use Query Builder to filter results $students = DB::table('students') ->when($class, function ($query, $class) { return $query->where('class', $class); }) ->orderBy('name', 'asc') ->get(); return view('students.search', compact('students')); } - Add a route:
Route::get('/students/search', [StudentController::class, 'search']); - Create a search form in a Blade view to accept user input.
In Tanzania, secondary schools often struggle to manage student records manually. By implementing database interaction as learned above, a school in Dodoma could build a web-based Student Record System. Teachers could use the "Create" function to register new students, the "Read" function to view class lists, and the "Update" function to correct student details if they transfer streams, replacing heavy paper-based logbooks with a fast, searchable digital system.
Jinsi utakavyotathminiwaTathmini ya mchakato · Tathmini ya matokeo · Tathmini ya maarifa
Tathmini ya mchakato
- Establish database connections using backend frameworks features.
- Implement basic CRUD operations.
- Optimize database queries for performance.
Tathmini ya matokeo
Database-driven web applications with fully functional CRUD operations and efficient query handling.
Tathmini ya maarifa
Detailed knowledge of:
Method used: The student should explain
- role of databases in web applications and the integration process.
Principles: The student should explain the principles of:
- Modular, secure, and scalable back-end architecture
Theories: The student should explain:
- concepts of database schemas, relationships, and query optimization.
Circumstantial knowledge:
Detailed knowledge about:
- challenges like handling large datasets, maintaining data integrity, and resolving connection issues.
Swali
Which file in a Laravel project is used to store the database connection details such as the database name, username, and password?
Ingia ili kuwasilisha jibu lako na lihesabiwe katika umahiri wako.
Ingia ili kufanya mazoeziMwalimu
Umekwama? Niulize chochote kuhusu mada hii.
Ingia ili kumuuliza Mwalimu wa AI wa Sonza kuhusu swali hili.
Ingia ili kuulizaMajadiliano
Hakuna maswali bado