Laravel 12 Model Full Tutorial – A Beginner’s Guide
In Laravel, Models are the backbone of any application. They interact with the database, handle business logic, and ensure smooth data operations. If you're new to Laravel, understanding Models is crucial for building robust web applications.
In this tutorial, we'll cover:
- What is a Model in Laravel?
- Creating a Model in Laravel 12
- Model Conventions & Configuration
- CRUD Operations with Eloquent ORM
- Model Relationships (One-to-One, One-to-Many, Many-to-Many)
- Mass Assignment & Fillable Fields
- Accessors & Mutators
- Query Scopes
- Soft Deletes
- Best Practices for Laravel Models
Let’s dive in!
1. What is a Model in Laravel?
A Model in Laravel represents a database table and provides an easy way to interact with it. Laravel uses Eloquent ORM (Object-Relational Mapping), which allows you to work with databases using an object-oriented syntax.
Key Features of Eloquent Models:
- Simple database operations (CRUD)
- Built-in relationships
- Automatic timestamps (
created_at,updated_at) - Mass assignment protection
- Query scopes for reusable conditions
2. Creating a Model in Laravel 12
To create a Model, use the make:model Artisan command:
php artisan make:model Post
This will generate a Post.php file in the app/Models directory.
Model with Migration
If you also want to create a migration (recommended), use:
php artisan make:model Post -m
This will generate:
app/Models/Post.php(Model)database/migrations/xxxx_create_posts_table.php(Migration)
3. Model Conventions & Configuration
Laravel follows convention over configuration, but you can customize settings.
Default Model Structure
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
// Model code here
}
Customizing Table Name
If your table name differs from the model name (e.g., blog_posts instead of posts), specify it:
protected $table = 'blog_posts';
Primary Key Customization
By default, Eloquent assumes id is the primary key. To change it:
protected $primaryKey = 'post_id';
Disabling Timestamps
If your table doesn’t have created_at and updated_at:
public $timestamps = false;
4. CRUD Operations with Eloquent ORM
Eloquent makes database operations simple.
Create (Insert)
$post = new Post;
$post->title = "Laravel Models";
$post->content = "This is a detailed guide.";
$post->save();
// Or use create() with fillable fields
Post::create([
'title' => 'New Post',
'content' => 'Content here'
]);
Read (Select)
// Get all posts
$posts = Post::all();
// Find by ID
$post = Post::find(1);
// Get first record matching condition
$post = Post::where('title', 'Laravel Models')->first();
// Get all posts where title contains 'Laravel'
$posts = Post::where('title', 'like', '%Laravel%')->get();
Update
$post = Post::find(1);
$post->title = "Updated Title";
$post->save();
// Or update directly
Post::where('id', 1)->update(['title' => 'New Title']);
Delete
$post = Post::find(1);
$post->delete();
// Or delete directly
Post::destroy(1);
5. Model Relationships
Laravel supports several relationship types:
One-to-One
Example: A User has one Profile.
// In User.php
public function profile()
{
return $this->hasOne(Profile::class);
}
// Usage
$user = User::find(1);
$profile = $user->profile;
One-to-Many
Example: A User has many Posts.
// In User.php
public function posts()
{
return $this->hasMany(Post::class);
}
// Usage
$user = User::find(1);
$posts = $user->posts;
Many-to-Many
Example: A Post can have many Tags, and a Tag can belong to many Posts.
// In Post.php
public function tags()
{
return $this->belongsToMany(Tag::class);
}
// Usage
$post = Post::find(1);
$tags = $post->tags;
6. Mass Assignment & Fillable Fields
To prevent security risks, Laravel requires you to define fillable fields.
protected $fillable = ['title', 'content'];
Alternatively, use $guarded to block specific fields:
protected $guarded = ['id'];
7. Accessors & Mutators
Accessor (Modify Retrieved Data)
public function getTitleAttribute($value)
{
return ucfirst($value); // Capitalize first letter
}
Mutator (Modify Before Saving)
public function setTitleAttribute($value)
{
$this->attributes['title'] = strtolower($value); // Convert to lowercase
}
8. Query Scopes (Reusable Filters)
// Local scope
public function scopePublished($query)
{
return $query->where('published', true);
}
// Usage
$publishedPosts = Post::published()->get();
9. Soft Deletes
Soft deletes allow you to "trash" records instead of permanently deleting them.
Enable Soft Deletes
- Add to the model:
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use SoftDeletes;
}
- Add
deleted_atcolumn in migration:
$table->softDeletes();
Querying Soft Deleted Records
// Get only trashed posts
Post::onlyTrashed()->get();
// Restore a post
Post::withTrashed()->find(1)->restore();
// Force delete
Post::withTrashed()->find(1)->forceDelete();
10. Best Practices for Laravel Models
- Keep models thin (move business logic to services).
- Use relationships instead of manual joins.
- Avoid complex queries in controllers (use scopes or repositories).
- Use fillable/guarded for security.
- Follow naming conventions (singular model names, plural table names).
Conclusion
Models in Laravel simplify database interactions with an elegant syntax. By mastering Eloquent, you can build scalable applications efficiently.
Happy coding! 🚀
Projects to explore next
Source-code projects from the KritiMyantra catalogue. Check each project's details before buying.
Flask Authentication System (Free Version) - Kritim Yantra
🛠 Features✔ Google & GitHub Authentication✔ User Registration & Login✔ Profile/Dashboard Access✔ Secure & Mi...
Python Flask Blog Project with Admin Panel
Are you ready to launch a powerful, modern, and fully customizable blog? Look no further! Introducing the Flask-Blog Pro...
Laravel 12 + ReactJS Starter Kit: Add Multi-Language Support (Arabic, English, Spanish) with Blog CRUD
🚀 Installation & Setup Download & Extract Get the ZIP from kritimyantra.com and extract it. Includes preconfigu...
Comments
No comments yet. Be the first to comment.
Sign in to join the discussion.