Hey Artisan,
In this quick guide to laravel eloquent default value if null, I will teach you laravel set default value in model attributes. let’s discuss how to set default value in model laravel. We will look at an example source code of laravel model set default value. I will help you to learn an example of how to add default value in laravel model.
You can use this source code with version of laravel 6, laravel 7, laravel 8 and laravel 9 versions. In this example, I will show you how to set the default eloquent model value in laravel version up to 5 to 9. We can use the $attributes
properties to set default value of model. So, we will create a posts table with title and body fields. then we will set default title from model.
app/Models/Post.php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
/**
* Write code on Method
*
* @return response()
*/
protected $fillable = [
'title', 'body'
];
/**
* The model's default values for attributes.
*
* @var array
*/
protected $attributes = [
'title' => 'Default Title',
];
}
Hope it can help you.
#laravel