How to write code gracefully, I think is the voice of every programmer. Ever since I first encountered Laravel 4.2 in early 2015, I’ve been hooked on the Laravel framework. I’ve always wanted to find a time to write about the use of Laravel and introduce the Laravel framework from the basics to the basics.

Today we’ll briefly talk about how to write Laravel code elegantly, using the Laravel-Admin plugin.

Create the Laravel project

Creating a Laravel project is easy as long as you follow the official documentation:

// Download Laravel installation program Composer Global Require using Composer"laravel/installer"// Create the Web project Laravel New WebCopy the code

The detailed configuration of the database is omitted

Laravel: d.laravel-china.org/docs/5.5/in…

How to install Composer can you see my previous article step by step Building a PHP server environment

Install laravel – admin

Laravel-admin is a quick tool to help you build back end management. It provides features such as page components and form elements to help you achieve a full back end management function with very little code.

Note: PHP 7+ and Laravel 5.5 are required for the current version (1.5)

Take a look at the laravel-Admin feature:

  • Built-in user and permission system
  • Model-grid supports fast building of data tables
  • Model-form supports fast building of data forms
  • Model-tree supports fast building of tree data
  • There are 40+ form element components built in, as well as support for extensions
  • Support for Laravel’s multiple model relationships
  • Supports multiple databases such as mysql, mongodb, and PGSQL
  • Supports the introduction of third-party front-end libraries
  • Web implementation of database and Artisan command line tool
  • Support for custom charts
  • A variety of common Web components
  • Supports local and OSS file upload

With these features, developing a background management system becomes relatively simple.

Install plug-in:

composer require encore/laravel-admin "1.5. *"PHP artisan vendor:publish --provider="Encore\Admin\AdminServiceProvider"// PHP artisan admin:installCopy the code

Simple three commands, you can configure a simple background management system, the account and password are admin

The code is concentrated in \APP\Admin

The default system provides a Dashboard screen:

<? php namespace App\Admin\Controllers; use App\Http\Controllers\Controller; use Encore\Admin\Facades\Admin; use Encore\Admin\Layout\Column; use Encore\Admin\Layout\Content; use Encore\Admin\Layout\Row; class HomeController extends Controller { publicfunction index()
    {
        return Admin::content(function (Content $content) {

            $content->header('Test Dashboard');
            $content->description('Description... ');

            $content->row(Dashboard::title());

            $content->row(function (Row $row) {

                $row->column(4, function (Column $column) {
                    $column->append(Dashboard::environment());
                });

                $row->column(4, function (Column $column) {
                    $column->append(Dashboard::extensions());
                });

                $row->column(4, function (Column $column) {
                    $column->append(Dashboard::dependencies()); }); }); }); }}Copy the code

Combining the interface and code, it can be seen that the interface is mainly divided into several parts: Header, Description, and two rows. The last row contains three column modules. The actual code is put in the Dashboard code as follows:

<? php namespace Encore\Admin\Controllers; use Encore\Admin\Admin; class Dashboard { /** * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public static function title()
    {
        return view('admin::dashboard.title'); } / * * * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public static function environment()
    {
        $envs= [['name'= >'PHP version'.'value'= >'PHP/'.PHP_VERSION],
            ['name'= >'Laravel version'.'value' => app()->version()],
            ['name'= >'CGI'.'value' => php_sapi_name()],
            ['name'= >'Uname'.'value' => php_uname()],
            ['name'= >'Server'.'value' => array_get($_SERVER.'SERVER_SOFTWARE')],

            ['name'= >'Cache driver'.'value' => config('cache.default')],
            ['name'= >'Session driver'.'value' => config('session.driver')],
            ['name'= >'Queue driver'.'value' => config('queue.default')],

            ['name'= >'Timezone'.'value' => config('app.timezone')],
            ['name'= >'Locale'.'value' => config('app.locale')],
            ['name'= >'Env'.'value' => config('app.env')],
            ['name'= >'URL'.'value' => config('app.url')]];return view('admin::dashboard.environment', compact('envs')); } / * * * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public static function extensions()
    {
        $extensions = [
            'helpers'= > ['name'= >'laravel-admin-ext/helpers'.'link'= >'https://github.com/laravel-admin-extensions/helpers'.'icon'= >'gears',].'log-viewer'= > ['name'= >'laravel-admin-ext/log-viewer'.'link'= >'https://github.com/laravel-admin-extensions/log-viewer'.'icon'= >'database',].'backup'= > ['name'= >'laravel-admin-ext/backup'.'link'= >'https://github.com/laravel-admin-extensions/backup'.'icon'= >'copy',].'config'= > ['name'= >'laravel-admin-ext/config'.'link'= >'https://github.com/laravel-admin-extensions/config'.'icon'= >'toggle-on',].'api-tester'= > ['name'= >'laravel-admin-ext/api-tester'.'link'= >'https://github.com/laravel-admin-extensions/api-tester'.'icon'= >'sliders',].'media-manager'= > ['name'= >'laravel-admin-ext/media-manager'.'link'= >'https://github.com/laravel-admin-extensions/media-manager'.'icon'= >'file',].'scheduling'= > ['name'= >'laravel-admin-ext/scheduling'.'link'= >'https://github.com/laravel-admin-extensions/scheduling'.'icon'= >'clock-o',].'reporter'= > ['name'= >'laravel-admin-ext/reporter'.'link'= >'https://github.com/laravel-admin-extensions/reporter'.'icon'= >'bug',].'translation'= > ['name'= >'laravel-admin-ext/translation'.'link'= >'https://github.com/laravel-admin-extensions/translation'.'icon'= >'language',]]; foreach ($extensions as &$extension) {
            $name = explode('/'.$extension['name']);
            $extension['installed'] = array_key_exists(end($name), Admin::$extensions);
        }

        return view('admin::dashboard.extensions', compact('extensions')); } / * * * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public static function dependencies()
    {
        $json = file_get_contents(base_path('composer.json'));

        $dependencies = json_decode($json.true) ['require'];

        return view('admin::dashboard.dependencies', compact('dependencies')); }}Copy the code

In this way, we can organize the code into pieces. Class Content implements Renderable

Other static resource files are stored in the /public/vendor/laravel-admin directory

For more information, see laravel-Admin’s website: laravel-admin.org/docs/#/zh/

Write a demo

With the Laravel-Admin plug-in, writing a list of movies can be done with just a few command lines, and it’s simple:

1. Create the model and create Migrations:

php artisan make:model Movie -mCopy the code

2. In Migrations, add the name field

<? php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateMoviesTable extends Migration { /** * Run the migrations. * * @return void
     */
    public function up()
    {
        Schema::create('movies'.function (Blueprint $table) {
            $table->increments('id');
            $table->string('name', 50)->unique();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('movies'); }}Copy the code

3. Run Migrations to create the corresponding database:

php artisan migrateCopy the code

4. If you have a data table, insert fake data into the table for testing

// Use this plugin to create fake data Composer require Fzaninotto /fakerCopy the code

5. Establish a Seeder

php artisan make:seeder MovieTableSeederCopy the code

In this class, create 1000 false data:

<? php use Illuminate\Database\Seeder; class MovieTableSeeder extends Seeder { /** * Run the database seeds. * * @return void
     */
    public function run()
    {
        //
        $faker = Faker\Factory::create();

        for($i = 0; $i < 1000; $i++) {
            App\Movie::create([
                'name'= >$faker->name ]); }}}Copy the code

Run:

php artisan db:seed --class=MovieTableSeederCopy the code

The table is filled with 1000 pieces of false data:

6. Create a resource Controller

php artisan admin:make MovieController --model=App\\MovieCopy the code

This gives you a basic Controller for adding, deleting, and editing movie lists.

7. The route is established

$router->resource('movies', MovieController::class);Copy the code

8. Add to the admin menu

Where the path should be noted:

The uri to part does not contain routing prefix paths, such as full path is http://localhost:8000/admin/demo/users, then fill in the demo/users, if you want to add external links, as long as the complete url, Such as laravel-admin.org/.

The image above also has the movies menu on the left.

This completes the simple background management of movie resources. In your browser, type the link: web.app/admin/movie…

You can see a complete list of movies:

Specifically, there are new, export, filter, operation (delete), undo, paging, modify, delete and other general functions, as shown in the following screenshot:

conclusion

With Laravel and Laravel-Admin, there is no need to write any code, and you can complete a “fully functional” resource operation background by tapping a few commands. Great convenience for our development.

The overall command line and code are as follows

php artisan make:model Movie -m

php artisan migrate

composer require fzaninotto/faker

php artisan make:seeder MovieTableSeeder

php artisan db:seed --class=MovieTableSeeder

php artisan admin:make MovieController --model=App\\Movie

$router->resource('movies', MovieController::class);Copy the code

Frameworks and open source plug-ins do sometimes make it easier for us to develop, so finding good frameworks and open source libraries can also boost our productivity.

For details on how the Laravel-Admin code is organized, refer to website development. According to the introduction of the official website, make good use of Laravel-Admin, then learn its source code and code design, finally take its essence, for your use.

“Finished”


Coding01 looks forward to your continued attention

qrcode


And thank you for seeing this

qrcode