onsa
12/19/2016 - 12:32 PM

Sample usage of Laravel Eloquent Model

Sample usage of Laravel Eloquent Model

<?php

// Don't remove delete users from the database, instead set a timestamp in the database to mark the entry as deleted.
use Illuminate\Database\Eloquent\SoftDeletingTrait;

class User extends \Eloquent {

  /**
  * The database table used by the model. Optional, if not given, the lowercase plural form of the classname is assumed.
  *
  * @var string
  */
  protected $table = 'app_users';
  
  /**
  * The primary key of the table. Optional, if not given, 'id' is assumed.
  *
  * @var string
  */
  protected $primaryKey = 'key';
  
  /**
  * Whether a self-incrementing key is to be used. Optional, true by default.
  *
  * @var boolean
  */
  protected $incrementing = false;
  
  /**
  * The database connection used by the model. Optional, to be given only in case the default connection is to be overriden.
  *
  * @var string
  */
  protected $connection = 'another_connection';
  
  /**
  * Whether created_at and updated_at timestamp columns are to be used. Optional, true is default.
  *
  * @var boolean
  */
  protected $timestamps = true;
  
  /**
  * Which related models when changed should update the updated_at timestamp on this table.
  *
  * @var array
  */
  protected $touches = array('note');
  
  /**
  * Database columns that can/cannot be mass assigned.
  *
  * @var array
  */
  protected $fillable/$guarded = array('first_name', 'last_name', 'email');
  
  /**
  * Database columns that are hidden/visible from conversion to array/json.
  *
  * @var array
  */
  // When hiding/showing relationships, use the relationship's method name, not the dynamic accessor name.
  protected $hidden/$visible = array('password');
  
  /**
  * Database column to fill in for soft deleted users.
  *
  * @var array
  */
  protected $dates = ['deleted_at'];
  
  /**
  * Function to override default date format.
  *
  * @var string
  */
  protected function getDateFormat()
    {
      return 'U';
    }
  
  /**
  * Reusable query.
  *
  * @var string
  */
  public function scopePopular($query, $popularity)
    {
      // do something with the existing query, for example a where condition
      return $query->where('votes', '>', $popularity);
    }
  
  // RELATIONSHIPS
  // One To One
  public function phone()
    {
      return $this->hasOne('Phone');
    }
  
  public function team()
    {
      // Second argument is optional and defines the foreign key on this table for finding the related model, by default team_id is assumed.
      // Third parameter defines the key on the parent table, by default id is assumed.
      return $this->belongsTo('Team', 'team_key');	
    }
  
  // One To Many
  public function notes()
    {
      return $this->hasMany('Note');
    }
  
  // Many to Many
  public function roles()
    {
      // A role_user table must be created first with user_id and role_id columns.
      // When the relationship is called by ->roles laravel will look up the caller model's id in the middle table, find the related target ids and return the targets from the target table.
      return $this->belongsToMany('Role');
        // Add columns on the pivot table (to be retrieved by ->pivot->expires).
        ->withPivot('expires', 'authorised_by');
        // Have the pivot timestamps automatically maintained.
        ->withTimestamps();
    }
  
  public function note_versions()
  {
    // A set of entries can be retrieved from a table not referenced by the caller table if an intermediate table is called.
    // Laravel finds all notes where notes.user_id = users.id - then it finds all versions where note_version.note_id = ids retrieved by previous query
    // Third and fourth parameters are optional, the keys on the intermediate and the taget tables respectively. By default user_id and note_id are assumed.
    return $this->hasManyThrough('NoteVersion', 'Note', 'user_key', 'note_number');
  }
  
  // add property not in DB
  // $this->attributes[‘new_field_1’] is an object containing laravel logic associated with the new field
  // $this->new_field_1 is the value itself
  protected $appends = [‘user_age’];
  
  // Accessor function to define how appended fields are to be computed or
  //  override how existing fields are to be read.
  public function getUserAgeAttribute() {
  // logic to calculate age from birthday
  }
  // Mutator function to override how existing fields are to be saved.
  public function setFirstNameAttribute() {
  // logic to mutate first name
  }	
}