Laravel 12 Model Full Tutorial – A Beginner’s Guide

Author

Kritim Yantra

Apr 01, 2025

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:

  1. What is a Model in Laravel?
  2. Creating a Model in Laravel 12
  3. Model Conventions & Configuration
  4. CRUD Operations with Eloquent ORM
  5. Model Relationships (One-to-One, One-to-Many, Many-to-Many)
  6. Mass Assignment & Fillable Fields
  7. Accessors & Mutators
  8. Query Scopes
  9. Soft Deletes
  10. 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

  1. Add to the model:
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
    use SoftDeletes;
}
  1. Add deleted_at column 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

  1. Keep models thin (move business logic to services).
  2. Use relationships instead of manual joins.
  3. Avoid complex queries in controllers (use scopes or repositories).
  4. Use fillable/guarded for security.
  5. 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! 🚀

Tags

Laravel Php

Comments

No comments yet. Be the first to comment!

Please log in to post a comment:

Continue with Google

Related Posts

How to Upload Images in Laravel 12: A Step-by-Step Guide
Kritim Yantra Kritim Yantra
Feb 28, 2025
Laravel 12 Multi-Auth System: Implementing Separate Admin and User Tables
Kritim Yantra Kritim Yantra
Feb 28, 2025
Understanding Laravel 12 Middleware
Web Development
Understanding Laravel 12 Middleware
Laravel Php
Kritim Yantra Kritim Yantra
Mar 05, 2025