1

I have a php laravel projekt where I need to add a field to one/more models (Eloquent). I don't have much experience in php and never tried laravel before.

The class looks like this now

class Player extends Eloquent
{
use GenderTrait;
use VisibilityTrait;
use PlayerPhotoTrait;
use PlayerActionTrait;

const GENDER_MALE = 2;
const GENDER_FEMALE = 1;

/**
 * The database table used by model.
 *
 * @var string
 */
protected $table = 'players';

/**
 * Parameters for `actions` relation.
 *
 * @see PlayerActionTrait::actions()
 * @var array
 */
protected $actionModel = [
    'name' => 'PlayerAction',
    'foreignKey' => 'player_id',
];

/**
 * The list of mass-assignable attributes.
 *
 * @var array
 */
protected $fillable = [
    'name',
    'start_value',
    'gender',
    'is_visible',
    'nation',
];

/**
 * The list of validation rules.
 *
 * @var array
 */
public static $rules = [
    'name' => 'required',
    'nation' => 'required|numeric',
    'start_value' => 'required|numeric',
];

/**
 * @inheritdoc
 */
protected static function boot()
{
    parent::boot();

}

/**
 * Players country.
 *
 * @return Country
 */
public function country()
{
    return $this->belongsTo('Country', 'nation');
}

/**
 * Player videos.
 *
 * @return mixed
 */
public function videos()
{
    return $this->morphMany('YoutubeLink', 'owner');
}
}

I would like to add a string field called "level" but I have no idea how to go about it. If I create the field in MySQL first and then the models get updated, if I update the models and then Laravel update MySQL for me?

Im looking forward to hearing what I can do :)

Alpo
  • 95
  • 1
  • 3
  • 11

1 Answers1

3

You need to add migration:

php artisan make:migration add_fields_to_players_table --table=players

Open in /database/migrations new migration and write

Schema::table('players', function ($table) {
    $table->string('new_string_field');
});

Now you need to run migrations

php artisan migrate

More info and available column types here

Michael Malov
  • 1,877
  • 1
  • 14
  • 20
  • Do you know if this is possible on a one.com server? – Alpo Jul 22 '16 at 14:22
  • one.com provides ssh access, so you able to run commands on your server – Michael Malov Jul 22 '16 at 14:46
  • Okay thanks, I'll try it when I get the chance. Will my Players table + model get updated automatically after I run the last command? – Alpo Jul 22 '16 at 16:28
  • Table will be update and new field will be accessible – Michael Malov Jul 22 '16 at 17:28
  • So after I run the command I need to add the new field in the "fillable" array and then I can access it in my controllers? – Alpo Jul 22 '16 at 18:24
  • When I try to call `php artisan make:migration` I get an error `[InvalidArgumentException] There are no commands defined in the "make" namespace.` EDIT: I tried to use `php artisan migrate:make` as it is larval 3 the project is running – Alpo Jul 22 '16 at 20:09