Skip to content

Database Table Management

Dan Alvidrez edited this page Nov 1, 2018 · 17 revisions

You can easily manage tables from controllers instead of using artisan if needed. The seeder in this example simply returns an array of arrays (database entries).

This example is from my personal working copy. I was using injection to pass the panel attributes from the WpHelper class. You can add a line to the addPanel methods to allow the attributes to be injected into your controllers:

$this->app
->when($closure)
->needs('$panel')
->give(compact(func_get_args()));

https://github.com/bayareawebpro/wp-lumen-plugin-framework/blob/master/app/Helpers/WpHelper.php#L182

<?php namespace App\Http\Controllers\Admin;
use App\Helpers\LumenHelper;
use App\Helpers\WpHelper;
use App\Http\Controllers\Controller;
class DatabaseController extends Controller{

    /**
     * @var $database \Illuminate\Database\DatabaseManager
     * @var $schema \Illuminate\Database\Schema\Builder
     * @var $files \Illuminate\Filesystem\Filesystem
     */
	protected $helper, $request, $panel, $database, $files, $tables, $schema, $wp;

	/**
	 * Create a new controller instance.
     * @param $helper LumenHelper
     * @param $wp WpHelper
	 * @param $panel object
	 */
	public function __construct(
	    LumenHelper $helper,
	    WpHelper $wp,
	    $panel, 
        ){
        $this->panel = $panel;
        $this->wp = $wp;
	$this->helper  = $helper;
        $this->request = $this->helper->request();
        $this->database = $this->helper->make('db');
        $this->files = $this->helper->make('files');
        $this->schema = $this->database->getSchemaBuilder();
	$this->data();
	$this->template();
	}

    /**
     * Process the Data
     */
	public function data(){
	    //Table Definitions & Schema Migration Callbacks
        $this->tables = (object) [
            'api_leads_entries' => (object) [
                'status' => false,
                'install' => function($table) {
                    /** @var $table \Illuminate\Database\Schema\Blueprint */
                    $table->increments('id');
                    $table->longText('request')->nullable();
                    $table->string('status', 191)->nullable()->default('null');
                    $table->timestamps();
                },
            ],
            'api_leads_locations' => (object) [
                'status' => false,
                'install' => function($table) {
                    /** @var $table \Illuminate\Database\Schema\Blueprint */
                    $table->increments('id');
                    $table->float('lat',11, 8);
                    $table->float('lng',11, 8);
                    $table->index(['lat', 'lng']);
                    $table->string('city', 191)->nullable()->default('null');
                    $table->string('county', 191)->nullable()->default('null');
                    $table->string('state', 191)->nullable()->default('null');
                    $table->string('zip', 5)->nullable()->default('null');
                },
                'seed' => [
                    'model' => \App\Models\Location::class,
                    'chunk' => 100,
                    'path' => database_path('seeds/locations.php'),
                ],
            ],
        ];

        //Migrate, Drop or Refresh Table Schema
		if($this->request->has('action') && $this->request->has('table')){

            $table = $this->request->get('table');
            $action = $this->request->get('action');


            //Drop Table
            if(in_array($action, array('refresh', 'drop'))){
                $this->schema->dropIfExists($table);
            }

            //Create Table
            if(in_array($action, array('install', 'refresh'))){
                $this->schema->create($table, $this->tables->$table->install);
            }

            //Seed Table
            if(in_array($action, array('install', 'refresh')) && isset($this->tables->$table->seed)){

                $path = $this->tables->$table->seed['path'];
                $model = $this->tables->$table->seed['model'];

                //Get the array from the file.
                $entries = collect($this->files->getRequire($path));

                //Break the array into chunks.
                $chunks = $entries->chunk($this->tables->$table->seed['chunk'])->toArray();

                //Insert the chunks into the database.
                $this->database->transaction(function() use ($chunks, $model){
                    foreach($chunks as $chunk){
                        app($model)->insert($chunk);
                    }
                });
            }

            //Flush Table
            if(in_array($action, array('flush'))){
                $this->database->table($table)->delete();
            }

            //Redirect
            $this->redirect(admin_url("admin.php?page={$this->panel->menu_slug}"));
		}

        //Get the status of each table.
        foreach(get_object_vars($this->tables) as $key => $value){
            if($this->schema->hasTable($key)){
                $this->tables->$key->status = "{$this->database->table($key)->count()} Rows";
            }
        }
	}

    /**
     * Display the Template
     */
	public function template(){
        echo $this->helper->view('admin.database', array(
		    'tables' => (array) $this->tables,
		    'panel' => (array) $this->panel,
        ));
	}
}

Layout

@extends('admin.layout')
@section('content')
    <p>This utility provides the ability to reset the custom database tables used by this plugin.</p>
    <table class="wp-list-table widefat striped">
        <thead>
        <tr>
            <th scope="col">Table</th>
            <th scope="col">Status</th>
            <th scope="col">Manage</th>
        </tr>
        </thead>
        <tbody>
            @foreach($tables as $table => $entry)
                <tr>
                    <td class="column-primary">
                        {{ $table }}
                    </td>
                    <td>
                        {{ $entry->status ? $entry->status : 'UnInstalled' }}
                    </td>
                    <td>
                        @if($entry->status)
                            <a href="{{ admin_url("admin.php?page={$panel->menu_slug}&action=refresh&table={$table}") }}"
                               onclick="return confirm('This will erase the table and reinstall the schema and seed data.    Are you sure?')"
                               class="button button-secondary">
                                ReFresh Schema
                            </a>
                            <a href="{{ admin_url("admin.php?page={$panel->menu_slug}&action=drop&table={$table}") }}"
                               onclick="return confirm('This will drop the database table.  Are you sure?')"
                               class="button button-secondary">
                                Drop Schema
                            </a>
                            <a href="{{ admin_url("admin.php?page={$panel->menu_slug}&action=flush&table={$table}") }}"
                               onclick="return confirm('This will flush the database table and delete all the entries.  Are you sure?')"
                               class="button button-secondary">
                                Flush Entries
                            </a>
                        @else
                            <a href="{{ admin_url("admin.php?page={$panel->menu_slug}&action=install&table={$table}") }}"
                               onclick="return confirm('Install the table schema and seed data.  Are you sure?')"
                               class="button button-primary">
                                Install Schema
                            </a>
                        @endif
                    </td>
                </tr>
            @endforeach

        </tbody>
    </table>

@endsection
Clone this wiki locally