Skip to content

Setting Default Values in Laravel 12 Eloquent Models

Learn how to set default values in Laravel 12 Eloquent models using $attributes, schema defaults, mutators, and events. Step-by-step guide with examples.

Dasun Kalupahana 2 min read 889 views 0 comments
On this page
  1. 1. Using the $attributes Property in the Model
  2. 2. Using Database Schema Defaults
  3. 3. Using Accessors and Mutators (Setters)
  4. 4. Using Model Events for Defaults
  5. Conclusion

Learn how to set default values in Laravel 12 Eloquent models using $attributes, database schema defaults, mutators, and model events. This in-depth guide includes practical examples and best practices to streamline your Laravel development. Perfect for developers looking to enhance their application’s data integrity and efficiency.


1. Using the $attributes Property in the Model

You can define default values directly in the Eloquent model by setting the $attributes property. This approach is simple and works well for static default values.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $attributes = [
        'status' => 'draft',
        'views' => 0,
        'is_published' => false,
    ];

    protected $fillable = [
        'title', 
        'content', 
        'status', 
        'views', 
        'is_published'
    ];
}

Usage:

Post::create([
    'title' => 'My First Post'
]);
// The post will have default values: 
// status = 'draft', 
// views = 0, 
// is_published = false

Explanation:

  • The $attributes array sets default values for the specified columns.
  • If a value is provided during creation, it overrides the default.
  • Use $fillable to allow mass assignment for the attributes.


2. Using Database Schema Defaults

You can set default values in the database schema itself during migration. This ensures defaults are applied at the database level.

Example Migration:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('content')->nullable();
            $table->string('status')->default('draft');
            $table->integer('views')->default(0);
            $table->boolean('is_published')->default(false);
            $table->timestamps();
        });
    }
};

Model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $fillable = ['title', 'content', 'status', 'is_published'];
}

Usage:

$post = Post::create(['title' => 'Database Default Post']);
// status = 'draft', views = 0, is_published = false (set by DB defaults)

Explanation:

  • The default() method in the migration sets database-level defaults.
  • If no value is provided, the database applies the default.
  • This approach is useful when you want defaults enforced regardless of the application logic.


3. Using Accessors and Mutators (Setters)

For dynamic or computed default values, you can use mutators (setters) to define logic when an attribute is set.

Example:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class Post extends Model
{
    protected $attributes = [
        'status' => 'draft',
        'is_published' => false,
    ];

    protected $fillable=['title', 'content', 'slug', 'status', 'is_published'];

    protected function slug(): Attribute
    {
        return Attribute::make(
            set: fn($value) => Str::slug($value),
        );
    }
}

Usage:

$post = Post::create([
    'title' => 'My Post',
    'slug' => 'test here',
]);

// Slug will be 'test-here'
  • The slug(): Attribute method defines a mutator for the slug column using Laravel’s Attribute class.
  • The set closure checks if a $value is provided; if not, it generates a URL-friendly slug from the title using Str::slug().
  • This approach ensures dynamic default values are applied during model creation or updates, leveraging modern PHP syntax for concise and readable code.


4. Using Model Events for Defaults

You can use model events like creating to set default values before saving to the database.

Example:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $fillable = ['title', 'content', 'published_at'];

    protected static function boot(): void
    {
        parent::boot();

        static::creating(function ($post) {
            $post->published_at = $post->published_at ?: now();
        });
    }
}

Usage:

$post = Post::create(['title' => 'Event-Based Post']);
// published_at will be set to the current timestamp

Explanation:

  • The creating event runs before the model is saved.
  • You can set defaults based on logic, such as the current time or user input.
  • This is useful for complex default value logic.


Conclusion

Setting default values in Laravel 12 Eloquent models is a powerful way to ensure data consistency and streamline development. By leveraging the $attributes property, database schema defaults, mutators, model events, and the modern Attribute casting approach, you can handle both static and dynamic defaults effectively. The Attribute class, with its concise syntax, offers a contemporary method to define dynamic defaults, such as generating slugs, while integrating seamlessly with other strategies. Whether you’re setting simple defaults like a post’s status or computing values like a URL-friendly slug, Laravel 12 provides flexible tools to meet your needs. Combine these methods based on your project’s requirements to maintain clean, maintainable, and efficient code.

 

If you found this helpful, feel free to share or drop a comment. Happy coding with Laravel! 🧱✨

Free resources for this topic

Code snippets and fixes for this topic

Get one practical tip every week

New tutorials, fixes and free cheat sheets from DEV Talk, straight to your inbox. No spam, unsubscribe in one click.

Free download: Laravel interview questions (PDF)

Have a question about this post?

Ask the community: other developers and the author can answer.

Ask the community

Get notified about new articles

One click, no email needed. Turn it off anytime with the bell at the top.

Get new articles on your iPhone

Add DEV Talk to your Home Screen, open it, then tap the bell.

Rate this post
0.0
Share

Enjoying the content?

If this article helped you, you can support the author with a coffee. It keeps new posts coming.

Buy me a coffee (opens in a new tab)

Comments 0

Be kind. Comments with links are reviewed before they appear.

No comments yet

Be the first to share your thoughts.

Get new articles in your inbox

Practical tutorials and deep dives, about once a week. No spam, unsubscribe anytime.

Privacy policy

Add DEV Talk to your Home Screen

  1. 1 Tap the Share button in Safari's toolbar.
  2. 2 Scroll down and tap Add to Home Screen.
  3. 3 Tap Add. Open it from the Home Screen to read like an app and to turn on notifications with the bell.

We use cookies to improve your experience and analyze traffic. By continuing, you agree to our Privacy Policy.