Eloquent Model Example

<?php
namespace App\Models;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;
use Illuminate\Database\Eloquent\Model;

use Carbon\Carbon;

class Members extends Model{
    protected $table = 'Test_Users';
    public static $table_name = "Test_Users";//For static functions
    protected $primaryKey = 'id';
    public $timestamps = true;
    const CREATED_AT = 'created_time';
    const UPDATED_AT = 'updated_time';
    //protected $dateFormat = 'M j Y h:i:s:000A';

    //$member->toArray() will include these relations automatically.
    protected $with = array('user_type_data', 'certs');

    const DT_TOTAL = 1;
    const DT_FILTERED = 2;

    //Fix for MSSQL Server
    public function getDateFormat()
    {
        return 'Y-m-d H:i:s.u';
    }

    //Fix for MSSQL Server
    public function fromDateTime($value)
    {
        return substr(parent::fromDateTime($value), 0, -3);
    }

    static function dt_items($options, $return_type=0){
       $result = DB::table(self::$table_name . ' as a')
            ->select(
                'a.*'
            );

        if($return_type == self::DT_TOTAL){
            return $result->count();
        }

        $keyword = val($options, 'keyword');
        if($keyword != false){
            $result = $result->where(function($query) use ($keyword){
                $find = '%' . $keyword . '%';
                $query->orWhere('a.user_name', 'like', $find);
                $query->orWhere('a.gid', 'like', $find);
                $query->orWhere('a.english_name', 'like', $find);
            });
        }

        if($return_type == self::DT_FILTERED){
            return $result->count();
        }

        if(val($options, 'sort') != false){
            $sorting = val($options, 'sort');
            foreach ($sorting as $key => $value) {
                $result = $result->orderBy($key, $value);
            }
        }else{
            $result = $result->orderBy('a.created_time', 'desc');
        }

        $result = $result->skip($options['start'])
            ->take($options['limit'])
            ->get();
        
        return $result;
    }

    static function datatable_sorting($columns, $order){
        $sort = array();
        foreach($order as $key => $item){
            $col_index = $item['column'];
            $dir = $item['dir'];
     
            $column = null;
            $column_key = null;
            $i = 0;
            foreach ($columns as $key => $item) {
                if($i == $col_index){
                    $column = $item;
                    $column_key = $key;
                    break;
                }
                $i++;
            }
     
            $sort[$column_key] = $dir;
        }
     
        return $sort;
    }

    static function datatable_data($data){
        $fields = Config::get('admin.member_table');

        $new_data = array();
        foreach($data as $item){
            $item_values = [];

            foreach ($fields as $key => $field) {
                $value = val($item, $key);

                if($key == 'status'){
                    $value = trans('front.order_status.' . $item->status);
                }

                if($field[2] == 'date'){
                    $value = Carbon::parse($value)->toDateString();
                }

                if($key == 'action'){
                    $value = '<div class="dropdown">
                            <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
                                選擇
                                <span class="caret"></span>
                            </button>
                            <ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
                                <li><a href="#" class="action edit" data-id="' . $item->id . '">Edit</a></li>' . 
                                '<li><a href="#" class="action certs" data-id="' . $item->id . '">Certifications</a></li>' . 
                                '<li><a href="#" class="action delete" data-id="' . $item->id . '">Delete</a></li>';
                    $value .= '</ul>
                        </div>';
                }

                $item_values[] = $value;
            }

            array_push($new_data, $item_values);
        }

        return $new_data;
    }

    //By array
	static function new_data($data){
		$data[self::CREATED_AT] = Carbon::now()->toDateTimeString();

		$result = DB::table(self::$table_name)
			->insertGetId($data);
		return $result;
	}

    //By array
	static function update_data($id, $data){
		$data[self::UPDATED_AT] = Carbon::now()->toDateTimeString();

		$result = DB::table(self::$table_name)
			->where('id', $id)
			->update($data);

		return $result;
	}

    //Relation. Function name must not in Member table columns.
    public function user_type_data()
    {
        return $this->belongsTo(
            'App\Models\UserType', 
            'user_type'//default: usertype_id in table Test_Users
        );
    }

    public function certs()
    {
        return $this->hasMany(
            'App\Models\MemberCerts', 
            //Foreign key in destination table
            //Default is "members_id" (by class name)
            'user_id'
        );
    }

    //https://laravel.com/docs/5.4/eloquent-relationships#one-to-many
    public function roles()
    {
        return $this->belongsToMany(
            'App\Models\RoleM', // Map to role table
            'user_roles', // Bridge table between users and roles
            'user_id', // foreign key for table users in table user_roles
            'user_group_id' // foreign key for table roles in table user_roles
        );
    }
}

Notes to get belongsToMany Data

Do not just use this script to retrieve data:

Auth::user()->roles();

Correct script:

Auth::user()->roles()->get();

Auth::user()->roles()->first()