Laravel Model: Everything You Need to Know π
In Laravel, Models are used for interacting with the database. They represent database tables and allow us to perform CRUD (Create, Read, Update, Delete) operations using Eloquent ORM.
1. What is a Model in Laravel?
A Model is a class that connects to a specific database table and allows you to interact with its records.
β
Example: A User
model interacts with the users
table.
π File: app/Models/User.php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
use HasFactory;
}
2. Creating a Model
To create a model, use the Artisan command:
php artisan make:model Product
This creates:
π app/Models/Product.php
To create a model with migration:
php artisan make:model Product -m
This also creates a migration file in database/migrations/
.
3. Database Table Mapping
By default, Laravel maps the model name to a table name (plural form).
β Example:
- Model:
Product
- Table:
products
If your table name is different, define it manually:
π File: app/Models/Product.php
class Product extends Model
{
protected $table = 'items'; // Custom table name
}
4. Mass Assignment Protection ($fillable
& $guarded
)
To allow mass assignment, define $fillable or $guarded:
β
Using $fillable
(Recommended)
class Product extends Model
{
protected $fillable = ['name', 'price', 'description'];
}
β
Using $guarded
(Alternative)
class Product extends Model
{
protected $guarded = []; // Allows all fields
}
5. Performing CRUD Operations with Eloquent
Create (Insert Data)
Product::create([
'name' => 'Laptop',
'price' => 50000,
'description' => 'A high-performance laptop'
]);
Read (Get Data)
$products = Product::all(); // Get all products
$product = Product::find(1); // Find by ID
$expensive = Product::where('price', '>', 30000)->get(); // Filter
Update (Modify Data)
$product = Product::find(1);
$product->price = 55000;
$product->save();
Or use mass update:
Product::where('id', 1)->update(['price' => 55000]);
Delete (Remove Data)
$product = Product::find(1);
$product->delete();
Or directly:
Product::destroy(1); // Delete by ID
Product::where('price', '<', 1000)->delete(); // Delete by condition
6. Model Relationships
Eloquent makes handling relationships between models easy.
One-to-One Relationship
π File: User.php
class User extends Model
{
public function profile()
{
return $this->hasOne(Profile::class);
}
}
One-to-Many Relationship
π File: Post.php
class Post extends Model
{
public function comments()
{
return $this->hasMany(Comment::class);
}
}
Many-to-Many Relationship
π File: User.php
class User extends Model
{
public function roles()
{
return $this->belongsToMany(Role::class);
}
}
7. Soft Deletes (Keeping Deleted Records)
To enable soft deletes, add the SoftDeletes
trait:
π File: app/Models/Product.php
use Illuminate\Database\Eloquent\SoftDeletes;
class Product extends Model
{
use SoftDeletes;
}
Run migration to add the deleted_at
column:
php artisan make:migration add_deleted_at_to_products_table --table=products
Now, instead of permanently deleting a record, Laravel marks it as deleted.
β Soft Delete
$product->delete(); // Moves to trash
β Restore Soft Deleted Record
Product::withTrashed()->where('id', 1)->restore();
β Force Delete (Permanent)
$product->forceDelete();
8. Query Scopes (Reusable Filters)
Scopes allow you to reuse queries across your project.
π File: Product.php
class Product extends Model
{
public function scopeExpensive($query)
{
return $query->where('price', '>', 50000);
}
}
β Use in Controller
$expensiveProducts = Product::expensive()->get();
Conclusion
β
Laravel Models make database interactions simple with Eloquent ORM.
β
Define database structure using $fillable
or $guarded
.
β
Use Eloquent methods for CRUD operations.
β
Establish relationships like One-to-One, One-to-Many, and Many-to-Many.
β
Use Soft Deletes and Query Scopes for advanced functionality.
π Need help with Laravel? Letβs build something amazing! π
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.