Search code examples
phplaravelmodeldatabase-migration

How does a Model know what migration it is associated with?


I apologize for the noob question. I am coming from the frontend and trying to improve my development skills by learning the backend. I am fairly new to PHP. I am having a hard time understanding how a Model knows which Migration it is associated with and vice versa? For example, how does a Model class know what table to write data to?


Solution

  • You might want to check the Illuminate\Database\Eloquent\Model class:

    // Copied from the framework.
    namespace Illuminate\Database\Eloquent;
    
    abstract class Model implements Arrayable, ArrayAccess, Jsonable, JsonSerializable, QueueableEntity, UrlRoutable
    {
    
        /**
         * The table associated with the model.
         *
         * @var string
         */
        protected $table;
    
        /**
         * Get the table associated with the model.
         *
         * @return string
         */
        public function getTable()
        {
            return $this->table ?? Str::snake(Str::pluralStudly(class_basename($this)));
        }
    }
    

    So if the $table instance variable is not set, the database table name to interact with will be calculated using the class name.