0

When I create a model, I want to check if the table exists in the DB. If it doesn't then I want to return a null. This is to prevent a record insert if the table doesn't exist yet.

In my model I have tried this. The Schema call returns false, but I'm still getting a model returned and not a null.

class SomeDataTable extends Model
{
  public function __construct($id)
  {
    $this->setTable($id);
    if (Schema::connection($this->connection)->hasTable($this->table) === false) {
      return null;
    }else{
      parent::__construct();
    }
  }

  public function setTable($id)
  {
    $this->table = $id.'_some_data_table';
  }
}

5
  • This is not a correct way to do this. You have to have table for model. Commented Mar 10, 2020 at 13:53
  • Right, that's why I'm trying to check if the table exists before I create a model. Commented Mar 10, 2020 at 14:06
  • if you are creating Model class you have to have table for it. i`m trying to thing tha reason why model may not have table Commented Mar 10, 2020 at 14:13
  • you cannot return null in constructor, constructor is used to initialize the object and its properties by assigning. When you want a object to become nullable. that means you want to destroying the object or clean up resources. Commented Mar 10, 2020 at 15:04
  • "This is to prevent a record insert if the table doesn't exist yet." Record definitely can't be inserted if table doesn't exist. Commented Mar 11, 2020 at 5:54

1 Answer 1

1

I'm not sure if you're looking for an ubiquitous solution. But what I'd do is do php aritsan migrate -m in the terminal to run migrations of all models. That way, all model tables are created by default.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.