Kritim Yantra
Apr 01, 2025
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:
Let’s dive in!
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.
created_at, updated_at)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.
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)Laravel follows convention over configuration, but you can customize settings.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
// Model code here
}
If your table name differs from the model name (e.g., blog_posts instead of posts), specify it:
protected $table = 'blog_posts';
By default, Eloquent assumes id is the primary key. To change it:
protected $primaryKey = 'post_id';
If your table doesn’t have created_at and updated_at:
public $timestamps = false;
Eloquent makes database operations simple.
$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'
]);
// 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();
$post = Post::find(1);
$post->title = "Updated Title";
$post->save();
// Or update directly
Post::where('id', 1)->update(['title' => 'New Title']);
$post = Post::find(1);
$post->delete();
// Or delete directly
Post::destroy(1);
Laravel supports several relationship types:
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;
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;
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;
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'];
public function getTitleAttribute($value)
{
return ucfirst($value); // Capitalize first letter
}
public function setTitleAttribute($value)
{
$this->attributes['title'] = strtolower($value); // Convert to lowercase
}
// Local scope
public function scopePublished($query)
{
return $query->where('published', true);
}
// Usage
$publishedPosts = Post::published()->get();
Soft deletes allow you to "trash" records instead of permanently deleting them.
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use SoftDeletes;
}
deleted_at column in migration:$table->softDeletes();
// Get only trashed posts
Post::onlyTrashed()->get();
// Restore a post
Post::withTrashed()->find(1)->restore();
// Force delete
Post::withTrashed()->find(1)->forceDelete();
Models in Laravel simplify database interactions with an elegant syntax. By mastering Eloquent, you can build scalable applications efficiently.
Happy coding! 🚀
No comments yet. Be the first to comment!
Please log in to post a comment:
Sign in with Google
Kritim Yantra
Kritim Yantra