Trait
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
namespace App\Traits; use Illuminate\Support\Facades\DB; use Carbon\Carbon; // To set $locale value of a model and translate all translatable attributes trait ModelBasis { static function new_item($data){ if(isset(self::$stimestamps) && self::$stimestamps == true){ $data['created_at'] = Carbon::now()->toDateTimeString(); } $result = DB::table(self::$stable) ->insertGetId($data); return $result; } static function update_item($id, $data){ if(isset(self::$stimestamps) && self::$stimestamps == true){ $data['updated_at'] = Carbon::now()->toDateTimeString(); } $result = DB::table(self::$stable) ->where('id', $id) ->update($data); return $result; } static function get_dt_sorting($req){ $columns = $req->input('columns'); $order = $req->input('order'); $sort_index = $order[0]['column']; $dir = $order[0]['dir']; $name = $columns[$sort_index]['data']; $sort = [ $name => $dir ]; return $sort; } static function gender_name($v){ if($v == 'f'){ return 'Female'; }elseif($v == 'm'){ return 'Male'; }else{ return ''; } } public function getTableColumns($table) { //$table = $this->getTable(); return $this->getConnection()->getSchemaBuilder()->getColumnListing($table); } public static function table_exists($table){ $result = DB::connection() ->getSchemaBuilder() ->hasTable($table); return $result; } public function add_change_log(){ $table = $this->getTable(); $fields = $this->getTableColumns($table); $log_table = $table . '_log'; //logg($this->getTable()); $data = []; foreach ($fields as $key => $field) { $data[$field] = $this->{$field}; } $data['changed_at'] = Carbon::now()->toDateTimeString(); $result = DB::table($log_table) ->insertGetId($data); return $result; } } |
Usage
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php namespace App; use Illuminate\Database\Eloquent\Model; use App\Traits\ModelBasis; class Caches extends Model { use ModelBasis; protected $primaryKey = 'id'; protected $table = 'caches'; static $stable = 'caches'; protected $fillable = ['call_no']; } |
SQL to Create a log table
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
DROP TABLE IF EXISTS `member_coupons_log`; CREATE TABLE `member_coupons_log` ( `table_id` int(11) NOT NULL AUTO_INCREMENT, `id` int(11) NOT NULL, `member_id` int(11) NOT NULL, `coupon_id` int(11) NOT NULL, `consumed` char(1) COLLATE utf8mb4_unicode_ci NOT NULL, `consumed_at` datetime DEFAULT NULL, `order_id` int(11) DEFAULT NULL, `created_at` datetime NOT NULL, `updated_at` datetime DEFAULT NULL, `changed_at` datetime DEFAULT NULL, PRIMARY KEY (`table_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; |