Showing posts with label table. Show all posts
Showing posts with label table. Show all posts

Monday, August 13, 2018

Laravel Models Eloquent Dynamically change table name

Some times you need to use one model for many tables, that means you want the same model but with many tables . So the property table will be dynamically set .to achieve this all you have to do is to use a trait that do the job as shown in the following code:

 

 /* DynamicTable.php */ 
 
trait DynamicTable
{
    protected $connection = null;
    protected $table = null;

    public function bind(string $connection, string $table)
    {
        $this->setConnection($connection);
        $this->setTable($table);
    }

    public function newInstance($attributes = [], $exists = false)
    {
        // Overridden in order to allow for late table binding.

        $model = parent::newInstance($attributes, $exists);
        $model->setTable($this->table);

        return $model;
    }

}


let's say our Model is called Profile :
require_once("DynamicTable.php"); 
 
class Profile extends Illuminate\Database\Eloquent\Model {
 
 use DynamicTable;
 
 public $timestamps = false; 
   
} 
 

Now, when you need to retrieve Model you will create a new object of this model and assign table and connection if the connection is different from default:
profiel1 = new Profile;
prfoile->setTable ("profile01");
profile->setConnection("mysql");
$results = $profile->find(123);

To insert data you can do the same .
Some retrieving commands will not work like all(), but you can use where(1,1) and it will do the job.

Saturday, August 17, 2013

SQLSTATE[42S02]: Base table or view not found: 1146 Table - Laravel Eloquent

If you got this error and you know for sure  that you are having the table name in your  database, Then the problem is the prefix of the table, why is that ?
I have my model declared like this :

class tableName extends Eloquent{} 

Now eloquent will take in account that table name in the database is table_names , As you see, it will add underscore before the capital letter and "s" for plural .this will happen by default unless you explicitly declare the name of the table inside the model class like this:

class tableName extends Eloquent{

protected $table = 'tableName'; 


}

Or Avoid the Capital letter in the name of the model.