Michael Ryan Soileau
Michael Ryan Soileau

Reputation: 1833

Laravel: Database [default] not configured when using an Eloquent model, but works on Facade

I have a model that extends Laravel's Eloquent model. When I attempt to use it, I get the error Database [default] not configured. However, when I simply call the DB facade, it works just fine. Code:

use Illuminate\Database\Eloquent\Model;

class Owners extends Model
{
    public $timestamps = false;
    protected $guarded = ['id'];
    protected $connection = 'default';

    public function records()
    {
        return $this->belongsTo(OwnersToRecords::class, 'owner_id', 'id');
    }

    public function zones()
    {
        return $this->belongsTo(OwnersToZones::class, 'record_id', 'id');
    }
}

When invoking by using $owner = new Owners, I get the error. When invoking by DB::table('owners'), the table works fine. So, what's wrong?

Upvotes: 3

Views: 3267

Answers (1)

peterm
peterm

Reputation: 92805

So, what's wrong?

This line is wrong, because there is no db connection with this name in your config/database.php file.

protected $connection = 'default';

Either remove it completely, in which case a default connection would be used, or specify a correct database connection name from your config file.

Note: Unless you have a very specific requirements i.e. working with multiple db's or absolutely need a separate independent connection for a model etc. you don't want to explicitly specify connection name in your model.

Upvotes: 4

Related Questions