How to fill a column automatically while creating records in Laravel

You can fill a column automatically while creating records in Laravel. Here we can use model observer to automatically fill the column data while you persist data to the database (e.g: slug).

Answers 1
  • Fill a column (slug) automatically while you persist (insert) data to the table in Laravel

    --PATH app\Models\Post.php
    use Illuminate\Support\Str;
    
    class Post extends Model
    {
        protected $fillable = [
            'title', 'slug', 'body'
        ];
    
        protected static function boot()
        {
            parent::boot();
            static::saving(function ($model) {
                $model->slug = Str::slug($model->title);
            });
        }
    
    }
    
    0

    This code snippet will automatically fill the slug column with data while creating records in the posts table. You have to create the posts table with fields title, slug and body. Use code snippets in the Post model. You can make changes as per your requirements.

    To create a records in posts table use the below code snippet.

    $post = App\Models\Post::create([
                'title' => 'lorem ipsum title',
                'body' => 'Lorem ipsum body'
            ]);
    
    dd($post);

    Output:

    #original: array:6 [▼
        "title" => "lorem ipsum title"
        "body" => "Lorem ipsum body"
        "slug" => "lorem-ipsum-title"
        "updated_at" => "2022-01-08 04:10:42"
        "created_at" => "2022-01-08 04:10:42"
        "id" => 24
      ]
  • Back to code snippet queries related laravel