Table of contents
In this post, I will share an example of how to add default eloquent model values on Laravel 8. If you want to add a default value of your model field value that is automatically added every time you save a record.
Â
This is one of the cool features of Laravel that can add a default value when we create a model instance. This is very useful to help to cleaner our code since we don't need to pass extra parameters to our Model but it appends automatically.
Â
With the example below create your migration first but you can skip it.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('description')->nullable();
$table->text('body');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
Â
Using the $attributes property you can define default values to your model.
Â
Here is the example below to add default eloquent model values.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
//...
/**
* The model's default values for attributes.
*
* @var array
*/
protected $attributes = [
'title' => 'Default Title',
];
//...
}
Â
Now let's test our code with default and without.
Â
In our routes/web.php we added the code below. This is for testing purposes only.
<?php
use App\Models\Post;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
Post::create([
'body' => 'post body'
]);
Post::create([
'title' => 'Manually title',
'body' => 'post body'
]);
$posts = Post::all();
foreach($posts as $post) {
echo 'title: '. $post->title . ', body: ' . $post->body . '<br>';
}
});
Â
As you can see in the first model creation we only pass the body attribute with value but in the second model creation, we included the title and body with each value.
Â
Here is the result below:
As you can see the first line result using the default value defined from our model. And the second was added manually.
Â
That's it I hope it helps. Thank you for reading :)
Read next