Home > other >  Laravel migration target column value as default value
Laravel migration target column value as default value

Time:10-25

I have table articles with these column id, title, details, slug, In my laravel migration default value can be set like:

$table->string('slug')->default('value');

Is there a way that default value is set by targeting specific column? or is it really possible? example: i want to set default value of slug the value of column id; So if i do

Articles::create(['id' => 'uuid-1', 'title' => 'article 1', 'details' => 'details article 1']);

I want that slug take 'uuid-1' as default value without passing by update after create

CodePudding user response:

You can simily use Eloquent creating method.

<?php
    
    namespace App\Model;
    
    use Illuminate\Database\Eloquent\Model;
    use App\User;
    use Illuminate\Support\Str;
    
    class Articles extends Model
    {
        protected static function boot() {
            parent::boot();
    
            static::creating(function ($article) {
                $article->slug = Str::slug($article->id);
            });
        }
    
    //The rest of methods

CodePudding user response:

Obviously I don't think that's possible. Because it is impossible for laravel to know its id before creating a record. But even if it's not a good practice, I can offer you a way. Instead of giving the default value in migration, you can add this code to the Article model:

    protected static function boot() {
        parent::boot(); // TODO: Change the autogenerated stub

        self::saving(function (Article $article){
            if ($article->getAttribute('slug') == null)
            {
                $lastrecord = Article::latest()->first();
                $slug = $lastrecord->id   1;
           
                $article->setAttribute('slug', $slug);
            }
        });
    }

This code will work when each article is created and will not do anything if a slug is sent. But if the slug is not sent, it will take the latest record, increase its id and create the slug and register it automatically. So you don't need any update process.

  • Related