public function import($entity) { $appHelper = new libs\AppHelper(); $className = $appHelper->getNameSpace() . $entity; $model = new $className(); $table = $model->getTable(); $columns = \Schema::getColumnListing($table); $key = $model->getKeyName(); $notNullColumnNames = array(); $notNullColumnsList = \DB::select(\DB::raw("SHOW COLUMNS FROM `" . $table . "` where `Null` = 'no'")); if (!empty($notNullColumnsList)) { foreach ($notNullColumnsList as $notNullColumn) { $notNullColumnNames[] = $notNullColumn->Field; } } $status = \Input::get('status'); $filePath = null; if (\Input::hasFile('import_file') && \Input::file('import_file')->isValid()) { $filePath = \Input::file('import_file')->getRealPath(); } if ($filePath) { \Excel::load($filePath, function ($reader) use($model, $columns, $key, $status, $notNullColumnNames) { $this->importDataToDB($reader, $model, $columns, $key, $status, $notNullColumnNames); }); } $importMessage = $this->failed == true ? \Lang::get('panel::fields.importDataFailure') : \Lang::get('panel::fields.importDataSuccess'); return \Redirect::to('panel/' . $entity . '/all')->with('import_message', $importMessage); }
public function test() { $columns = \Schema::getColumnListing('tp_goods'); // echo '<pre>'.print_r($columns,true).'</pre>'; $columns = implode("', '", $columns); echo $columns; }
public static function boot() { self::creating(function ($custom_field) { if (in_array($custom_field->db_column_name(), Schema::getColumnListing(DB::getTablePrefix() . CustomField::$table_name))) { //field already exists when making a new custom field; fail. return false; } return DB::statement("ALTER TABLE " . DB::getTablePrefix() . CustomField::$table_name . " ADD COLUMN (" . $custom_field->db_column_name() . " TEXT)"); }); self::updating(function ($custom_field) { //print(" SAVING CALLBACK FIRING!!!!! "); if ($custom_field->isDirty("name")) { //print("DIRTINESS DETECTED!"); //$fields=array_keys($custom_field->getAttributes()); //; //add timestamp fields, add id column //array_push($fields,$custom_field->getKeyName()); /*if($custom_field::timestamps) { }*/ //print("Fields are: ".print_r($fields,true)); if (in_array($custom_field->db_column_name(), Schema::getColumnListing(CustomField::$table_name))) { //field already exists when renaming a custom field return false; } return DB::statement("UPDATE " . CustomField::$table_name . " RENAME " . self::name_to_db_name($custom_field->get_original("name")) . " TO " . $custom_field->db_column_name()); } return true; }); self::deleting(function ($custom_field) { return DB::statement("ALTER TABLE " . CustomField::$table_name . " DROP COLUMN " . $custom_field->db_column_name()); }); }
/** * Display a listing of the resource. * GET /pages * * @return Response */ public function index() { //set data & columns datatables $data['exclude_columns'] = array("", "password", "remember_token", "created_at", "updated_at"); $data['json_columns'] = $this->array2Columns(Schema::getColumnListing('users'), $data['exclude_columns']); $data['json_data'] = $this->result2datatables(User::all()->toArray()); return View::make(Config::get('srm.theme_directory') . 'users.index', $data); }
/** * Check if model's table has column * * @param \Eloquent $model * @param string $column * @return bool */ public static function hasColumn($model, $column) { $table = $model->getTable(); $columns = \Cache::remember('amigridview.columns.' . $table, 60, function () use($table) { return \Schema::getColumnListing($table); }); return array_search($column, $columns) !== false; }
public function writeExcel() { dd(\Schema::getColumnListing()); Excel::create('Filename', function ($excel) { $excel->sheet('Sheetname', function ($sheet) { // Sheet manipulation }); })->store('xlsx', storage_path('excel')); }
public static function export($table, $dbConnection = 'default') { $data = DB::connection($dbConnection)->table($table)->get(); $csv = \League\Csv\Writer::createFromFileObject(new \SplTempFileObject()); $csv->insertOne(\Schema::getColumnListing($table)); foreach ($data as $row) { $csv->insertOne((array) $row); } $csv->output($table . '-' . date('YmdHi') . '.csv'); }
/** * Show the form for creating a new resource. * * @return Response */ public function create() { $people = bbStock::all(); $csv = \League\Csv\Writer::createFromFileObject(new \SplTempFileObject()); $csv->insertOne(\Schema::getColumnListing('bbstock')); foreach ($people as $person) { $csv->insertOne($person->toArray()); } $csv->output('bbstock.csv'); }
public function getData() { $draw = Input::get('draw'); if (Input::get('order') && Input::get('columns')) { $columns = Input::get('columns'); $sort_cri = Input::get('order'); if ($sort_cri[0]) { $sort_field = $columns[$sort_cri[0]['column']]['data']; $sort_order = $sort_cri[0]['dir']; } } $length = Input::get('length'); $start = Input::get('start'); $search_fields_or_search_text = Input::get('searchFields'); if (isset($limitFrom) && isset($rec_per_page) && isset($search_fields_or_search_text)) { if (is_array($search_fields_or_search_text)) { $usertotal_search_query = User::query(); $userdata_search_query = User::query(); foreach ($search_fields_or_search_text as $search_field => $search_value) { $totalUsers = $usertotal_search_query->where($search_field, 'LIKE', '%' . $search_value . '%'); $users = $userdata_search_query->where($search_field, 'LIKE', '%' . $search_value . '%'); } $totalUsers = $usertotal_search_query->count(); $users = $userdata_search_query->skip($limitFrom)->take($rec_per_page)->get(); } else { $user_fields = \Schema::getColumnListing('users'); $usertotal_search_query = User::query(); $userdata_search_query = User::query(); foreach ($user_fields as $user_field) { $totalUsers = $usertotal_search_query->orWhere($user_field, 'LIKE', '%' . $search_fields_or_search_text . '%'); $users = $userdata_search_query->orWhere($user_field, 'LIKE', '%' . $search_fields_or_search_text . '%'); } $totalUsers = $usertotal_search_query->count(); $users = $userdata_search_query->skip($limitFrom)->take($rec_per_page)->get(); } } else { if (isset($start) && isset($length) && isset($sort_field) && isset($sort_order)) { $totalUsers = User::count(); $users = User::orderBy($sort_field, $sort_order)->skip($start)->take($length)->get(); } else { if (isset($start) && isset($length)) { $totalUsers = User::count(); $users = User::skip($start)->take($length)->get(); } else { $totalUsers = User::count(); $users = User::all(); } } } return ['draw' => (int) $draw, 'recordsFiltered' => $totalUsers, 'recordsTotal' => $totalUsers, 'data' => $users]; }
public function getData() { $sort_field = Input::get('sortField'); $sort_order = Input::get('sortOrder'); $rec_per_page = Input::get('recPerPage'); $current_page = Input::get('currentPage'); $limitFrom = ($current_page - 1) * $rec_per_page; $search_fields_or_search_text = Input::get('searchFields'); if (isset($limitFrom) && isset($rec_per_page) && isset($search_fields_or_search_text)) { if (is_array($search_fields_or_search_text)) { $usertotal_search_query = User::query(); $userdata_search_query = User::query(); foreach ($search_fields_or_search_text as $search_field => $search_value) { $totalUsers = $usertotal_search_query->where($search_field, 'LIKE', '%' . $search_value . '%'); $users = $userdata_search_query->where($search_field, 'LIKE', '%' . $search_value . '%'); } $totalUsers = $usertotal_search_query->count(); $users = $userdata_search_query->skip($limitFrom)->take($rec_per_page)->get(); } else { $user_fields = \Schema::getColumnListing('users'); $usertotal_search_query = User::query(); $userdata_search_query = User::query(); foreach ($user_fields as $user_field) { $totalUsers = $usertotal_search_query->orWhere($user_field, 'LIKE', '%' . $search_fields_or_search_text . '%'); $users = $userdata_search_query->orWhere($user_field, 'LIKE', '%' . $search_fields_or_search_text . '%'); } $totalUsers = $usertotal_search_query->count(); $users = $userdata_search_query->skip($limitFrom)->take($rec_per_page)->get(); } } else { if (isset($limitFrom) && isset($rec_per_page) && isset($sort_field) && isset($sort_order)) { $totalUsers = User::count(); $users = User::orderBy($sort_field, $sort_order)->skip($limitFrom)->take($rec_per_page)->get(); } else { if (isset($limitFrom) && isset($rec_per_page)) { $totalUsers = User::count(); $users = User::skip($limitFrom)->take($rec_per_page)->get(); } else { $totalUsers = User::count(); $users = User::all(); } } } return ['userCount' => $totalUsers, 'users' => $users]; }
public function search($input, $getResults = true) { $query = Discuss::query(); $columns = Schema::getColumnListing('discusses'); $attributes = array(); foreach ($columns as $attribute) { if (isset($input[$attribute]) and !empty($input[$attribute])) { $query->where($attribute, $input[$attribute]); $attributes[$attribute] = $input[$attribute]; } else { $attributes[$attribute] = null; } } if ($getResults) { return [$query->get(), $attributes]; } else { return $query; } }
/** * @param \Illuminate\Database\Query\Builder $query * @param string $table join the table * @param string $one joins first parameter * @param string|array|null $operatorOrCollumns operator condition or collums list * @param string $two joins two parameter * @param string $type join type (left, right, '', etc) * @param bool|false $where custom where condition * @param array $collumns if you will not pass collumns, it will retreive the collumn listing. If you pass null * it will not get any data from the model. * * @return \Illuminate\Database\Query\Builder */ public function scopeJoinWithSelect($query, $table, $one, $operatorOrCollumns, $two, $type = "left", $where = false, $collumns = array()) { // if the operator collumns are in if (is_array($operatorOrCollumns) || is_null($operatorOrCollumns)) { $collumns = $operatorOrCollumns; $operatorOrCollumns = "="; } if (!is_null($collumns)) { // if there is no specific collumns, lets get all if (empty($collumns)) { $collumns = \Schema::getColumnListing($table); } // build the table values prefixed by the table to ensure unique values foreach ($collumns as $related_column) { $query->addSelect(new Expression("`{$table}`.`{$related_column}` AS `{$table}.{$related_column}`")); } } return $query->join($table, $one, $operatorOrCollumns, $two, $type, $where); }
/** * Execute the console command. * * @return void */ public function fire() { $userClass = config('auth.model'); if (!$userClass) { $userClass = config('auth.providers.users.model'); } $list = \Schema::getColumnListing('users'); $list2 = array_filter($list, function ($e) { return $e != 'id' && !str_contains($e, 'password'); }); $user = new $userClass(); $passWord = $this->secret('Password'); $user->password = Hash::make($passWord); foreach ($list2 as $option) { if ($this->option($option)) { $user->{$option} = $this->option($option); } } $user->save(); $this->comment($user->id); }
public function settings($table) { if (!Schema::hasTable($table)) { $this->data['result'] = 0; $this->data['message'] = 'Specified table not found'; } else { $this->data['result'] = 1; $this->data['message'] = ''; $this->data['table_name'] = $table; $users_columns = Schema::getColumnListing($table); if (DB::table("crud_table_rows")->where('table_name', $table)->count() <= 0) { foreach ($users_columns as $column) { DB::table('crud_table_rows')->insert(['table_name' => $table, 'column_name' => $column, 'type' => 'text', 'create_rule' => '', 'edit_rule' => '', 'creatable' => true, 'editable' => true, 'listable' => true, 'created_at' => Utils::timestamp(), 'updated_at' => Utils::timestamp()]); } } $columns = DB::table("crud_table_rows")->where('table_name', $table)->get(); foreach ($columns as $column) { if ($column->type == "radio") { $radios = DB::table("crud_table_pairs")->where("crud_table_id", $column->id)->get(); $column->radios = $radios; } if ($column->type == "checkbox") { $checkboxes = DB::table("crud_table_pairs")->where("crud_table_id", $column->id)->get(); $column->checkboxes = $checkboxes; } if ($column->type == "range") { $range = DB::table("crud_table_pairs")->where("crud_table_id", $column->id)->first(); $column->range_from = $range->key; $column->range_to = $range->value; } if ($column->type == "select") { $selects = DB::table("crud_table_pairs")->where("crud_table_id", $column->id)->get(); $column->selects = $selects; } } $this->data['columns'] = $columns; $this->data['table'] = $this->table; } return View::make('tables.settings', $this->data); }
public function export_data_excel(Request $request) { header('Content-type: application/vnd.ms-excel'); header('Content-Disposition: attachment; filename="GiftProjectDump_' . date("YmdHis") . '.xlsx"'); header('Cache-Control: max-age=0'); $excel = new PHPExcel(); $add = function (&$array, $table, $row, $key) { if ($key == 'password') { return; } $array[] = $row->getAttributeValue($key); }; foreach (['App\\Household', 'App\\HouseholdAddress', 'App\\Child', 'App\\HouseholdPhone', 'App\\User'] as $model) { $table = (new $model())->getTable(); $sheet = new PHPExcel_Worksheet($excel, $table); $columns = \Schema::getColumnListing($table); $sheet->fromArray($columns, NULL, 'A1'); $i = 2; foreach ($model::all() as $row) { $array = array(); foreach ($columns as $key) { $add($array, $table, $row, $key); } $sheet->fromArray($array, NULL, 'A' . $i++); } Export::AutoSizeSheet($sheet); $excel->addSheet($sheet); } $excel->removeSheetByIndex(0); $writer = new PHPExcel_Writer_Excel2007($excel); $writer->setOffice2003Compatibility(true); $writer->save('php://output'); // TODO: How else can I tell Laravel to let me write the response? flush(); exit(0); }
public function availableFields($include_eagers = true) { $columns = []; $model = app($this->model); $model_table = $model->getTable(); foreach (Schema::getColumnListing($model->getTable()) as $column) { $columns[$model_table][$column] = $column; } if ($include_eagers) { foreach ($this->eagers->lists('name') as $relationship_string) { $temp_model = $model; foreach (explode('.', $relationship_string) as $relationship) { $temp_model = $temp_model->{$relationship}()->getRelated(); } foreach (Schema::getColumnListing($temp_model->getTable()) as $column) { $columns[$relationship_string][$relationship_string . '#' . $column] = $column; } } } return $columns; }
<?php // require('http://localhost:8000/app/libs/excel/Classes/PHPExcel.php'); set_time_limit(1020); require app_path() . '/libs/excel/Classes/PHPExcel.php'; $objPHPExcel = new PHPExcel(); // Set document properties $objPHPExcel->getProperties()->setCreator("ideconnect.com")->setLastModifiedBy("ideconnect.com")->setTitle("Office 2007 XLSX Test Document")->setSubject("Office 2007 XLSX Test Document")->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")->setKeywords("office 2007 openxml php")->setCategory("Test result file"); // Add some data //*************************************************************************************** $excelarr = array(); $hotelbookings = Hotelbooking::where('eventname', '=', $event)->get(); $headers = Schema::getColumnListing('hotelbookings'); foreach ($hotelbookings as $hotelbooking) { $arr = array(); foreach ($hotelbooking['attributes'] as $key => $value) { $arr[] = $value; } $excelarr[] = $arr; } array_unshift($excelarr, $headers); $objPHPExcel->setActiveSheetIndex(0)->fromArray($excelarr, '', 'A1'); $objPHPExcel->getActiveSheet()->setTitle('DM'); $styleArray = array('font' => array('name' => 'Calibri', 'size' => '10', 'color' => array('rgb' => 'FFFFFF'), 'bold' => true), 'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'startcolor' => array('rgb' => '000000'))); // $styleArray2 = array( // 'font' => array( // 'name' => 'Calibri', // 'size' => '10', // 'color' => array( // 'rgb' => '000000' // ),
static function update($where = null, $object, $updates) { $auth = self::auth(); if (isset($auth)) { $permission = 0; if ($where == 'my') { $permission = 1; $objects = $object::where($own, "=", Auth::user()->id); } else { if ($where == "*") { $permission = 2; $objects = $object::whereRaw("1 = 1"); } else { if (is_object($where)) { if (isset($where->permission)) { $permission = $where->permission; } else { $permission = 0; } $objects = $where; } else { throw new \RuntimeException('Only "me", "*", or an object.'); } } } $auth = Authorization::get_auth("update", $auth, $permission, get_class_name($object)); $select = $auth['fields']; $own = $auth['own']; if (count($select) == 0) { abort(403); } $real_updates = array(); $real_fields = \Schema::getColumnListing($object->getTable()); foreach ($updates as $key => $value) { if (in_array("*", $select) || in_array($key, $select)) { if (in_array($key, $real_fields)) { $real_updates[$key] = $value; } else { return response('"' . get_class_name($object) . '" has no "' . $key . '" property', 403); } } } $result = $objects->update($real_updates); if ($result) { return $result; } else { abort(403); } } }
public function export(Request $request, $race_id) { $race = Race::find($race_id); if ($request->has('format')) { $runners = Runner::where([['race_id', $race_id], ['status', 1]])->get(); $csv = Writer::createFromFileObject(new \SplTempFileObject()); if ($request->get('format') == 'excel_win') { $csv->setDelimiter(';'); $csv->setOutputBOM(Writer::BOM_UTF8); } $csv->insertOne(\Schema::getColumnListing('runners')); foreach ($runners as $runner) { $csv->insertOne($runner->toArray()); } $csv->output($race->prefix . '_runners.csv'); die; } return view('admin.export'); }
public static function getColumn() { $table = Schema::getColumnListing("int_event_dinas"); return $table; }
public function showTable($table_name) { $columns = \Schema::getColumnListing($table_name); $rows = \DB::table($table_name)->get(); return view('print_table', compact('columns', 'rows')); }
| $default_random: Fields that if no data is set, they will be randomly generated (10 characters) +-------------------+ | $su_hidden: Columns that will be added to the hidden array if the user is su +------------------+ | $columns: the row columns +--+ | $fields: get the available fields | | | +---------------------------------------------------------------------------+ | | | This file creates the variables nessesary to make | | the dynamic field edition avialable to all the controllers | | regardless of it's differences. | | | +---------------------------------------------------------------------------+ */ include 'SimpleGet.php'; # Get the row table columns $columns = Schema::getColumnListing($table); # Add su_hidden to hidden if the row is su if (Schema::hasColumn($table, 'su') and $row->su) { # Add the su_hidden fields to the hiden variable foreach ($su_hidden as $su_hid) { array_push($hidden, $su_hid); } } # Gets the fields available to edit / update $final_columns = []; foreach ($columns as $column) { $add = true; foreach ($hidden as $hide) { if ($column == $hide) { $add = false; }
public function postIssuesList($mobile = false) { $query = Issues::where('pid', '=', Session::get('pid'))->where('issue_date_inactive', '=', '0000-00-00 00:00:00')->get(); $result = ''; if ($query) { if ($mobile == false) { $result .= '<ul>'; foreach ($query as $row) { $result .= '<li>' . $row->issue . '</li>'; } $result .= '</ul>'; } else { $list_array = []; $form = []; $i = 1; $columns = Schema::getColumnListing('issues'); $row_index = $columns[0]; $list_array[] = ['label' => 'Add Issue', 'pid' => Session::get('pid'), 'href' => action('MobileController@editpage', array('issues', $row_index, ''))]; foreach ($query as $row) { $list_array[] = ['label' => $row->issue, 'pid' => Session::get('pid'), 'href' => action('MobileController@editpage', array('issues', $row_index, $row->{$row_index}))]; } $result .= $this->mobile_result_build($list_array, 'mobile_issues_list'); } } else { $result .= ' None.'; } echo $result; }
public function getShowRecommend($id) { $recommend = Recommend::find($id); $columns = Schema::getColumnListing('recommend'); return View::make('admin.show_recommend')->with('recommend', $recommend)->with('columns', $columns); }
function fillable_fields($ins_name, $d, $ins_type = 'i') { return array_only($d, Schema::getColumnListing(table_name($ins_name, $ins_type))); }
<?php \Larakit\CRUD\CrudRow::register(\Larakit\Models\Entity::class, '/admincp/entities'); define('ROUTE_ADMIN_CODEGEN', 'larakit::admin.codegen'); \Larakit\Route\Route::item(ROUTE_ADMIN_CODEGEN)->setBaseUrl('/admincp/generator')->put()->addSegment('{model}')->put(); define('ROUTE_ADMIN', 'larakit::admin'); \Larakit\Route\Route::item(ROUTE_ADMIN)->setBaseUrl('/admincp/')->put(); \Adminlte\Widget\WidgetSidebarMenu::group('ГЕНЕРАТОР КОДА')->addItem('codegen', 'Модели', ROUTE_ADMIN_CODEGEN); return; $ret = []; foreach (Schema::getColumnListing('bmmaket-core__recommend_groups') as $name) { $ret[$name] = Schema::getColumnType('bmmaket-core__recommend_groups', $name); } dd($ret); dd(DB::table('bmmaket-core__recommend_groups'));
/** * Execute the console command. * * @return mixed */ public function handle() { $this->info('0%: Generador de Nodos iniciado.'); $this->info('20%: Las tablas fueron limpiadas.'); $nodes = \Solunes\Master\App\Node::get(); $total_count = 0; \App::setLocale('es'); $languages = \Solunes\Master\App\Language::get(); $menu_dashboard = \Solunes\Master\App\Menu::create(['menu_type' => 'admin', 'permission' => 'dashboard', 'icon' => 'dashboard']); foreach ($languages as $language) { \App::setLocale($language->code); $menu_dashboard->translateOrNew($language->code)->name = trans('master::admin.dashboard'); $menu_dashboard->translateOrNew($language->code)->link = 'admin'; } \App::setLocale('es'); $menu_dashboard->save(); foreach ($nodes as $node) { if ($node->location == 'package') { $lang_folder = 'master::model.'; } else { $lang_folder = 'model.'; } foreach ($languages as $language) { \App::setLocale($language->code); $node->translateOrNew($language->code)->singular = trans_choice($lang_folder . $node->name, 1); $node->translateOrNew($language->code)->plural = trans_choice($lang_folder . $node->name, 0); } \App::setLocale('es'); $node->save(); $table_name = $node->table_name; $columns = \Schema::getColumnListing($table_name); if ($node->type == 'field') { $count = 0; foreach ($columns as $col) { $count = \FuncNode::node_field_creation($table_name, $node, $col, 0, $count, $languages); } $total_count += $count; } else { $model = $node->model; $initiated_model = new $model(); // CREAR MENU \FuncNode::node_menu_creation($node, $languages); // MENU CREADO, CREAR COLUMNAS $count = 0; foreach ($columns as $col) { if ($col != 'site_id') { $count = \FuncNode::node_field_creation($table_name, $node, $col, 0, $count, $languages); } } // REVISAR SI TIENE TRADUCCION Y SI SE DEBEN CREAR ESOS CAMPOS TAMBIEN if (property_exists($model, 'translatedAttributes')) { $node->translation = 1; $node->save(); foreach ($initiated_model->translatedAttributes as $col) { if ($col != 'site_id') { $count = \FuncNode::node_field_creation(str_replace('-', '_', $node->name) . '_translation', $node, $col, 1, $count, $languages); } } } // AGREGAR PARENT A DONDE CORRESPONDE if (count($node->children) > 0) { foreach ($node->children as $child) { $count++; $multiple = false; if ($child->type == 'field') { $child_value = str_replace($node->name . '-', '', $child->name); $child_value = str_replace('-' . $node->name, '', $child_value); } else { $child_value = $child->name; } if ($child->type == 'subchild') { $multiple = true; } $field = new \Solunes\Master\App\Field(); $field->parent_id = $node->id; $field->name = $child->table_name; $field->trans_name = str_replace($node->name . '-', '', $child->table_name); $field->type = $child->type; $field->order = $count; $field->multiple = $multiple; $field->value = $child_value; $field->save(); } } $total_count += $count; } $node->load('fields'); foreach ($node->fields as $field) { $saved = false; if (!$field->label) { if ($node->location == 'package') { $lang_folder = 'master::fields.'; } else { $lang_folder = 'fields.'; } foreach ($languages as $language) { \App::setLocale($language->code); $field->translateOrNew($language->code)->label = trans($lang_folder . $field->trans_name); } \App::setLocale('es'); $saved = true; } if ($saved === true) { $field->save(); } } } $this->info('95%: Se importara el excel de nodes para corregir los campos.'); $this->info(\FuncNode::load_nodes_excel(base_path(config('solunes.vendor_path') . '/src/nodes.xlsx'))); $this->info(\FuncNode::load_nodes_excel(public_path('seed/nodes.xlsx'))); $this->info('100%: Se crearon ' . $total_count . ' campos.'); }
/** * Append relationship field, if necessary, to a given stub * * @param string $stub * @param string $relationship_to_create * @param string $entity * @param string $table * @param array $relationship * @param null|string $module */ private function appendRelationshipFieldsToStub(&$stub, $relationship_to_create, $entity, $table, $relationship, $module = null, $is_translation = false) { if (is_null($module)) { $module = "asgardgenerators"; } // ensure lowercase $relationship_to_create = strtolower($relationship_to_create); $isHasMany = $relationship_to_create === 'hasmany'; $isBelongsToMany = $relationship_to_create === 'belongstomany'; // init defaults switch ($relationship_to_create) { case 'belongstomany': case 'hasmany': $view_name = 'select-multiple'; $selected = '[]'; break; case 'belongsto': case 'hasone': default: $view_name = 'select'; $selected = 'null'; break; } //singular or plural model function? $function = camel_case($table); $function = $isHasMany || $isBelongsToMany ? str_plural($function) : str_singular($function); $isTranslationRelation = ends_with($function, 'Translations') || ends_with($function, 'Translation'); $relatedModelColumns = \Schema::getColumnListing($table); //skipping translation fields if (!$isTranslationRelation && !$isHasMany) { // determine the primary key(s) try { $primary_key = $this->tables->primaryKey($relationship[0]); } catch (DatabaseInformationException $e) { // fallback to the default id primary key name $primary_key = 'id'; } $list_keys = ''; if (is_array($primary_key) && !empty($primary_key)) { $list_keys = "'" . implode("','", $primary_key) . "'"; } elseif (!is_array($primary_key)) { $list_keys = "'{$primary_key}'"; } $options = 'null'; if (!empty($list_keys)) { $keysCount = count(explode(',', $list_keys)); if ($keysCount === 1) { $textColumn = $this->getListColumn($list_keys, $relatedModelColumns); $lists = "{$textColumn},{$list_keys}"; $options = "\$" . str_plural($function) . '->lists(' . $lists . ')->toArray()'; $selected = "\$" . $entity . '->' . $function . '()->lists("id","id")->toArray()'; } } $primary_key = $this->arrayToString($primary_key); $single = $this->entityNameFromTable($relationship[0]); $name = $isBelongsToMany ? $function : $relationship[1]; $stub .= "@include('{$module}::partials.fields.{$view_name}', [\n 'title' => '{$single}',\n 'name' => '{$name}', //{$function},//'{$relationship[0]}',\n 'options' => {$options},\n 'primary_key' => {$primary_key},\n 'selected' => {$selected},\n ])\n\n"; } else { //skipping translation multiple-select field, or hasMany field } }
/** * @return array|mixed */ public function getDBColumns() { if (!isset($this->dbColumns)) { $this->dbColumns = \Cache::remember($this->cacheKey . '_db_columns', 10080, function () { return \Schema::getColumnListing($this->getTable()); }); } return $this->dbColumns; }
public function getComponent($alias) { $alias_mix = []; preg_match('/([\\d\\w]+)\\/([\\d\\w]+)\\.js/', $alias, $alias_mix); if (count($alias_mix) != 3) { return; } $class_name = $alias_mix[2]; $model_full_name = $this->getModelFullName($class_name); if (!$model_full_name) { $model_full_name = $this->getModelFullName($class_name . 'Model'); } switch (strtolower($alias_mix[1])) { case 'store': $content = view('ext.data.Store', ['model_name' => $class_name]); break; case 'treestore': $content = view('ext.data.TreeStore', ['model_name' => $class_name]); break; case 'grid': $grid_columns = []; if ($model_full_name) { $model = new $model_full_name(); if (property_exists($model, 'grid_columns')) { $grid_columns = $model->grid_columns; } } $content = view('ext.grid.Panel', ['class_name' => $class_name, 'columns' => $grid_columns]); break; case 'tree': $content = view('ext.tree.Panel', ['class_name' => $class_name]); break; case 'model': $fields_str = ''; if ($model_full_name) { $model = new $model_full_name(); $column_listing = \Schema::getColumnListing($model->getTable()); $fields = array_diff($column_listing, $model->getHidden()); $fields_str = '"' . implode('","', $fields) . '"'; } $content = view('ext.data.Model', ['model_name' => $class_name, 'fields' => $fields_str]); break; case 'treemodel': $fields_str = []; if ($model_full_name) { $model = new $model_full_name(); $column_listing = \Schema::getColumnListing($model->getTable()); $fields = array_diff($column_listing, $model->getHidden()); if (property_exists($model, 'tree_text_field')) { $fields[] = ['name' => 'text', 'mapping' => $model->tree_text_field]; } $fields_str = json_encode($fields); } $content = view('ext.data.TreeModel', ['model_name' => $class_name, 'fields' => $fields_str]); break; case 'controller': // break; } return response($content, 200)->header('Content-Type', 'application/javascript'); }