How to Set Default Value of Column in Laravel Model?

December 22, 2022
Laravel
How to Set Default Value of Column in Laravel Model?

In this quick guide, will be explaining how you can set the default value of the column in the laravel.

There is quite need when you need to set the default value of the column for example when you are adding the article and if no category is mentioned you want to assign some default value like uncategorized.

So the end of the article you will have able to set the default value of a column in laravel model.

Lets get started!

Assumption

Lets assume that we have Article Model which is tied with article table. And lets we have category column in that table. We want the category to be ‘uncategorized’ in case no category was passed to Article::create().

[also_read href=”https://impulsivecode.com/get-last-1-5-10-or-more-records-of-database-table-in-laravel/” title=”How to Get last 1,5,10 or more records of database table in Laravel?”]

How to Set Default Value of Column in Laravel Model?

In the model, we have the option of adding attributes in which we can mention the column names in which we want to set the default value of a column in laravel model.

<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class Article extends Model
{
    use HasFactory;
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    protected $fillable = [
        'title','content','category','slug'
    ];
  
    /**
     * The model's default values for attributes.
     *
     * @var array
     */
    protected $attributes = [
        'cateogory' => 'uncategorized',
    ];
}

In the above code, We have set the default value of category to be ‘uncategorized’.

So if we call the controller Article::create() method, in which if we set the value of category the column then it will override the attributes default value.

But if we don’t mention the category, then it will use the default value that we assigned in the attributes array of the model.

Conclusion

Hope you have learned in the above how to set the default value of the column in the laravel model.

See you soon at the next one 🙂


Write a Reply or Comment

Your email address will not be published. Required fields are marked *


Icon