Najmi
Najmi

Reputation: 207

laravel 5.4: seeding for inheritance model return error

I have created base model and extend all my model from base model in laravel 5.4. When i do db:seed i got error

Trying to get property of non-object

. Anyone know why it happens? it is db:seed did not support model inheritance.

Base Model:

    <?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Auth;

class BaseModel extends Model
{
    public static function boot()
     {
        parent::boot();
        static::creating(function($model)
        {
            $model->created_by = Auth::user()->id;
            $model->updated_by = Auth::user()->id;
        });
        static::updating(function($model)
        {
            $model->updated_by = Auth::user()->id;
        });   
        static::deleting(function($model)
        {
            $model->deleted_by = Auth::user()->id;
            $model->save();
        });
    }
}

Model:

    <?php

namespace App;

use Illuminate\Database\Eloquent\SoftDeletes;

class Bank extends BaseModel
{
    use SoftDeletes;

    public static function boot()
    {
        parent::boot();
    }
}

Seeder:

    <?php

use Illuminate\Database\Seeder;
use App\Bank as Bank;

class BanksTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Bank::create( [
            'name' => 'xxxxxxxx' ,
        ] );
    }
}

Upvotes: 0

Views: 417

Answers (1)

Thomas Van der Veen
Thomas Van der Veen

Reputation: 3226

Probably it has to do with Auth::user()->id. db:seed is executed in terminal and has no authenticated user, therefore Auth::user() will return NULL. Do a check before setting created_by and updated_by.

static::creating(function($model)
{
    if (Auth::user())
    {
        $model->created_by = Auth::user()->id;
        $model->updated_by = Auth::user()->id;
    }
});

Hope this helps :)

Upvotes: 2

Related Questions