Laravel Models and Database Records

Lesson 25 of 50 - Learn how to create models, configure tables, and manage database records in Laravel.

50%
1. What Is a Laravel Model?

A model is a PHP class that represents and interacts with a database table. Laravel models usually extend the Eloquent Model class.

Models help you:

  • Retrieve database records.
  • Insert new records.
  • Update existing records.
  • Delete records.
  • Define relationships between tables.

For example, a Student model typically represents the students table, while a Course model typically represents the courses table.

Models are commonly stored in the app/Models directory.

2. Create a Model Using Artisan

Use the following command to create a Student model.

php artisan make:model Student

Laravel creates:

app/
    Models/
        Student.php

Example model code:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    //
}

The model inherits database functionality from Laravel's Eloquent Model class.

Laravel conventionally maps the Student model to the students table.

3. Model Naming and Table Names

By default, Laravel converts a model's class name into a plural, snake-case table name.

Model Default Table
Student students
Course courses
Product products
Category categories
OrderItem order_items

If your database uses a different table name, specify it using the $table property.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    protected $table = 'student_details';
}

This model now uses the student_details table instead of students.

4. Configure Primary Keys and Timestamps

By default, Eloquent expects the primary key to be named id. It also expects the table to have created_at and updated_at timestamp columns.

If your table uses a different primary key, configure the model accordingly.

class Student extends Model
{
    protected $primaryKey = 'student_id';
}

If the primary key is not an auto-incrementing integer, additional properties may be needed.

class Student extends Model
{
    protected $primaryKey = 'student_id';

    public $incrementing = false;

    protected $keyType = 'string';
}

To disable automatic timestamp handling when the table does not contain the standard timestamp columns, use:

public $timestamps = false;

Only change these settings when they match your actual database schema.

5. Configure Mass Assignment

Mass assignment allows you to create or update model attributes using an array of values.

Example Student model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    protected $fillable = [
        'name',
        'email',
        'phone',
        'course',
    ];
}

The $fillable array specifies which attributes can be assigned through methods such as create() and update().

Example:

Student::create([
    'name' => 'Rahul Kumar',
    'email' => 'rahul@example.com',
    'phone' => '9876543210',
    'course' => 'Python',
]);

Ensure that these columns exist in the students table. Never allow users to mass-assign sensitive fields such as administrator permissions without proper safeguards.

6. Use a Model to Insert and Retrieve Records

After configuring your model and database table, you can insert and retrieve records using Eloquent.

Insert a new student:

$student = Student::create([
    'name' => 'Amit Kumar',
    'email' => 'amit@example.com',
    'phone' => '9876543210',
    'course' => 'Web Development',
]);

Retrieve all students:

$students = Student::all();

Retrieve one student by ID:

$student = Student::find(1);

Retrieve one student or return a not-found exception:

$student = Student::findOrFail(1);

These examples assume the model's table and columns are configured correctly.

7. Update and Delete Records

Retrieve a model, change its attributes, and save it to update the database record.

$student = Student::findOrFail(1);

$student->name = 'Priya Sharma';
$student->course = 'Python';

$student->save();

You can also update using the model's update method:

$student = Student::findOrFail(1);

$student->update([
    'name' => 'Priya Sharma',
    'course' => 'Python',
]);

Delete a student:

$student = Student::findOrFail(1);

$student->delete();

The update example uses mass assignment, so the updated attributes must be allowed by the model. Deletion permanently removes the record unless soft deletes are configured.

8. Add Casts and Hide Sensitive Fields

Model casts automatically convert selected attribute values into useful PHP types when accessed through Eloquent.

class Student extends Model
{
    protected $casts = [
        'is_active' => 'boolean',
        'admission_date' => 'date',
    ];
}

This example assumes that the corresponding columns exist in the database table.

You can also hide sensitive attributes when the model is converted to an array or JSON.

class Student extends Model
{
    protected $hidden = [
        'password',
        'remember_token',
    ];
}

The $hidden property helps prevent these attributes from appearing in serialized model output. It does not replace authorization or other security checks.

9. Model Commands and Practical Assignment

Useful Artisan commands:

Command Purpose
php artisan make:model Student Create a model.
php artisan make:model Student -m Create a model with a migration.
php artisan make:model Student -mf Create a model, migration, and factory.
php artisan make:model Student -mfs Create a model, migration, factory, and seeder.

Practical Assignment:

  1. Create a Student model.
  2. Connect it to a students table using Eloquent conventions.
  3. Configure the model's fillable attributes.
  4. Insert a new student record.
  5. Retrieve all students and find a student by ID.
  6. Update the student's course and save the changes.
  7. Delete a test student record.
  8. Configure casts and hide sensitive attributes where appropriate.

Test your operations using a development database and avoid deleting real student records while practising.

Quick Quiz

1. Which class do Laravel Eloquent models usually extend?




2. Which property specifies the model's mass-assignable attributes?




3. Which property specifies a custom database table name?