Building Laravel Apps in an 80/20 fashion

Danquah Bernard White
Encounters with Laravel
10 min readAug 15, 2018

--

Give your applications a touch of Professionalism in a real fastway — using laravel Generators

Automation is a modern trend in software development, mostly popularized by the Python Guys. Nevertheless, Laravel is here for good, hence infyomlabs/laravel-generator package brings you automated way to build almost 95% of the core components of your application. If you’ve been around the development block for sometime and you are bit trendy, you will be well aware of how some core components such APIs development, API documentation, setting up CRUD operations, writing test cases, migrations, Models, Controllers and the repository design pattern can quickly become messy.

Let me begin by sharing a story of how missing off this core components in your application can easily render you as Bad Ass Programmer.

It was in my Level 300 days at KNUST, when a senior course mate, a geek in the hood, @Yu0San, contacted me to assist him on a project he wanted to use to contest against the then Startup Battlefield Africa edition held in 2017. I quickly arrived, where he sought to take a look at my previous projects in laravel. During the time, I was working on a project work for one MIT Student. The guy was so porous that I did not want to bore him with more architectural jargons and components… so I skipped using things like the repository pattern and wrote one long pregnant controllers, a thing I’ve seen most Laravel kids do.

Oh yes, immediately I saw the dude’s face change. He can smell the menstruation. The code structure ain’t great. Some key elements such as repositories were missing. Long story, short he saw me as an amateur. I lost my shine. Lets get over this roadblock with less code — using Infyomlabs/laravel-generator package.

In this post, I will be covering how to use infyomlabs/laravel-generator package to:

  • To create a full fledged backend components for your application using this time only 20% of your normal efforts.
  • Generate models, controllers, repositories and form request classes from our migrations
  • Generate a an Admin dashboard for our application without coding a single line of HTML/CSS and JavaScript

Getting Started

In the few sections which follow, we will be stepping through how to automate the creation of the major components of your application including full-fledged models with important properties such as fillables, cast, and model level relationship methods, already made controllers, extensible CRUD repositories and Form Request classes for use in your controllers.

All the above-mentioned components are going to be scaffold from our migrations since they are the most basic elements that shape our domain. As a bonus, we will be generating a simple dashboard like web pages for our app.

For our example program, we will go with simple blog post system as an illustration.

Creating the Application

I assume you know Laravel basics. Go ahead and create your Laravel application using composer. I named my own my-simple-blog, and make sure your database connections are configured in your .env file.

You can confirm that the setup went well by running php artisan tinkerin the console. Then tinker with the DB connection by running

DB::connection()->getPdo();

If everything goes on well you should see something like the output below.

Overview of our App

Let's say our simple blog will keep track of posts written by authors on the platform — we support collaborations between authors on writing posts. The users of our app includes both visitors and authors as well administrators. Each post can have a set of comment(s) written by user(s). The diagram below gives a summary.

We are keeping it simple here. You may check the GitHub repository for the full implementation — including other business logic. Now lets dive into the nitty-grittys.

First things First — Applying 80/20 Principle

The 80/20 Principle also known as the Pareto principle — the law of vital few is a very important rule for productivity.

What are the few dozen things? — Jim Rohn

In our case we are going use fewer components of our entire laravel application code to maximize productivity.

The generator package gives us the power to use our migration classes (<20%)to generate models, controllers, repositories, form requests, and even dashboard views(all this comprising about 80% of our application code).

Ain’t this magic -); Yeah…Lets go make magic happen.

Creating Migrations

We will start by creating roles migration, since most other entities rest on this table.

php artisan make:migration create_roles_table --create=roles

I passed the --create flag to tell artisan to use snippets for creating new table. We will be using this convention for subsequent tables.

A little note — laravel installs with already made users and password reset migration files, and since laravel runs our migration files from top to down using the date prefixes on the migration files, we’ve got to override that by renaming our roles migration year prefix. I changed mine from 2018_08_15_042444 to 2013_08_15_042444. So as to place the roles file as an earlier migration. When done correctly your file system should look something like this.

Make the roles migration file come on top by changing the year prefix to an earlier year such as 2013
Creating the roles table
Creating Users Table
Update users table

Laravel recommends a different migration file with table flag to create your foreign key references. This table addes a role_id to the users table.

Creating the posts table
Creating the comments table

The comments table is updated to contain the post_id and user_id foreign keys. The post_id will refer to the Post Article under which a user wants to comment, and the user_id refers to the user who wants to write a comment.

The other tables left are about collaborative authoring of a blog post. Thus, we want to track which authors collaborated to write a particular post. We do that by creating apost_authors table.

Create Post Authors Table

This is the whole collection of migration files for our project. The UpdatePostAuthors table keeps track of which authors wrote on a Post, in one — to — many fashion as we will soon see in the generated model classes. This section marks an estimated effort of about 15% work done on our project. The remaining 5% which together makes the vital 20% involves installing and publishing packages, which we are going to do in a breeze.

Installing Generator Packages

Add the following packages into your composer.json file.

"require": {
"infyomlabs/laravel-generator": "5.6.x-dev",
"laravelcollective/html": "^5.6.0",
"infyomlabs/adminlte-templates": "5.6.x-dev",
"infyomlabs/swagger-generator": "dev-master",
"jlapp/swaggervel": "dev-master",
"doctrine/dbal": "~2.3"
}

Once you have added the this packages. Go ahead and run composer update.

The packages added into the require block of our composer.json file contains stuff that will help generate our application components. This is handled by the laravel-generator package.

doctrine/dbalpackage specifically works with laravel-generator package to enable us to generate our apps core components from migration tables.

The laravelcollective/html and adminlte-template will help us a generate a nice dashboard frontend for the admin usage.

This are all biolerplate code, you can tweak it out to fit your style. In the proceeding sections we will go through the steps on how to do just that, by simply sitting behind the console and issuing commands and doing some small changes to theconfig files.

Add service providers & aliases

Add following service providers into your providers array in config/app.php

Collective\Html\HtmlServiceProvider::class,
Laracasts\Flash\FlashServiceProvider::class,
Prettus\Repository\Providers\RepositoryServiceProvider::class,
\InfyOm\Generator\InfyOmGeneratorServiceProvider::class,
\InfyOm\AdminLTETemplates\AdminLTETemplatesServiceProvider::class,

Add following alias to aliases array in config/app.php

'Form'      => Collective\Html\FormFacade::class,
'Html' => Collective\Html\HtmlFacade::class,
'Flash' => Laracasts\Flash\Flash::class,

Run the following command to publish all installed thirdparty packages:

php artisan vendor:publish

Having published all required packages accordingly. Its now time to tell composer to generate some stuff.

php artisan infyom:publish

You will get a prompt like the one shown below asking you to select which providers or files you want to publish. You should choose InfyOmGeneratorServiceProvider and the RepositoryServiceProvider. If you are not sure what to choose, select option 0 (zero) by typing it and on hitting the enter key.

On publishing your vendor libraries

With the side effects of this command, this will create a laravel_generator.php under config/infyom folder. The content of this file can be customized. Let’s discuss some of the key properties of this file:

  • The path array contains paths to the various directories where the generated components will be placed. If you are not comfortable with the defaults, you are free to change them.
  • The namespaces array is also configurable to your likes. The namespaces matches the various components in the paths. So be careful, when you make changes to this values.
  • The templates section describes the front-end framework style you would like to use. We installed the AdminLTETemplate. But there are various alternatives including bootstrap, material and metronic templates. You my check it out on the documentation site. You just have install them using composer and then replace the template option with the appropriate template library name. Since we will be generating a dashboard view for our app. Lets go ahead and publish the layouts — this setup things such as navigation menu and base layouts to use for the views.
  • Before publishing layouts make sure the add_on > menu option is set to true It is usually true by default. Now publish the layout files by running
php artisan infyom.publish:layout

It will prompt you some overrides are going to happen in the routes web.php type y for prompt and you will be through.

The remaining options are pretty much straight forward.

An AppBaseController.php is created and added to your controllers folders. Controllers to be generated in the sections ahead will all inherit from this base controller instead of the default one. It command also creates a ApiTestTrait.php in your tests folder to be used for testing.

This is just the beginning The real stuff comes next.

Generating Application Stuff

This is where real fun and magic happens. We will be generating our models, controllers, repositories and form request classes based on our migrations.

The 80/20 Principle at work. No coding just commands. Sit back and relax.

Generating components from table

The command syntax to use is

php artisan infyom:scaffold $MODEL_NAME --fromTable --tableName=$TABLE_NAME

where $MODEL_NAME will be the name of the model to be generated and $TABLE_NAME is the table name we want to base the model, controllers and repositories on so lets go ahead just type into our console.

Starting with the roles table. We will type:

php artisan infyom:scaffold Role --fromTable --tableName=roles

The command will scaffold all the major laravel application component for the table under concern. The --fromTable flag allows all this to happen. The are other options to generating tables too. The --tableName specifies which table to use. When done correctly, you should see something like this in your console.

All the important moving parts of your model has been generated for you based on your table. Model, Repository, Form Request, Controlle, Views and Routes. TIS GREAT! The models will be placed in a Models folder and Repositories inside of the Repositories folder. All this extends from a provisioned base classes. In your resources/views directory you should see roles folder which contains views for the all the CRUD operations and tables.

Go ahead and repeat that for the all your tables.

And that is all, you have a full fledge application, easily extendable and editable.

Lets take a look at the generator interface. The magic done by AdminLTETemplate

http://127.0.0.1:8000/register
http://127.0.0.1:8000/login
Roles Listings View

You may check the code source on GitHub for line to comparison.

One story before I conclude…

Just last month a I joined a team to work on a project which was to be built using laravel. I was the asked to create a RESTful APIs to be consumed the client applications. The team was surprised when I called an hour later telling them I’m done. — The trick they didn’t know it was the power of laravel generators. Add it to your developer toolbox.

Let me know how I did!

Hoping that this article is beneficial to people out there interested in Laravel Generators, and provides some fundamentals and sparks some ideas on how y’all could use this excellent tool in your apps/projects!

This was my first authored article, so let me know how I can improve!

I’d love to continue this topic and explore API development documentation, — specifically using Swagger Framework, paired with the JSON web Tokens package. There’s some really cool and powerful stuff going on there in my opinion! Let me know if there’d be interest in that topic.

Acknowledgements

Also big thanks to @de_kubi, @atigahmaxwell and @JosBash my team mates at AilenTech Startup Grind, for encouraging me to pursue this. Y’all continue to exceed all expectations of what a great team can achieve, and I honestly love getting up every morning knowing that together, we’re going to crush it.

--

--