Home > Software design >  Illuminate\Database\QueryException with message 'SQLSTATE[42P01]: Undefined table: 7 ERROR: r
Illuminate\Database\QueryException with message 'SQLSTATE[42P01]: Undefined table: 7 ERROR: r

Time:11-07

My code is written in PHP using Laravel and Postgresql as the db.

I have a model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    use HasFactory;
    protected $fillable = [
        'last_name',
        'first_name',
        'phone_number',
        'address',

    ];
    //protected $table = 'database.contact';
    protected $hidden = [

        'remember_token',
    ];
}

and a migration:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class Contact extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('contact ',function(Blueprint $table){
              $table->id();
              $table->string('first_name');
              $table->string('last_name');
              $table->integer('phone_number');
              $table->ipAddress('address')->nullable();
              $table->rememberToken();

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
         Schema::dropIfExists('contact');
    }
}

but when I run in terminal :

php artisan tinker

Then:

Contact::create(['last_name' => 'joe', 'first_name' => 'ajoe.com', 'phone_number' => 88552])

I get the error:

Illuminate\Database\QueryException with message 'SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "contacts" does not exist LINE 1: insert into "contacts" ("last_name", "first_name", "phone_nu... ^ (SQL: insert into "contacts" ("last_name", "first_name", "phone_number", "updated_at", "created_at") values (joe, ajoe.com, 88552, 2021-11-06 21:00:43, 2021-11-06 21:00:43) returning "id")'

If you have any idea why this is happening, I would love to get it Thanks .

CodePudding user response:

add this line in model

protected $table = 'contact';

CodePudding user response:

first step: remove the extra space from the table name in your migration:

 Schema::create('contact ',function(Blueprint $table){

to:

 Schema::create('contact',function(Blueprint $table){

then, in your Contact model, set the $table property:

class Contact extends Model
{
   

    /*
    |--------------------------------------------------------------------------
    | GLOBAL VARIABLES
    |--------------------------------------------------------------------------
    */

    protected $table = 'contact';
  • Related