megacolorboy

Abdush Shakoor's Weblog

Writings, experiments & ideas.

Integrate Excel into your Laravel project

Before you integrate Excel into your application, make sure your project meets the following requirements:

  • PHP v7.0 or greater
  • Laravel v5.5 or greater
  • PhpSpreadsheet v1.6 or greater

Download the package

Download the maatwebsite/excel package using Composer:

composer require maatwebsite/excel

Add it to service provider

By default, this will be done automatically when you're installing the package but if you want to do it yourself, add this in your config/app.php file:

<?php
// ...
'providers' => [
    // ...
    Maatwebsite\Excel\ExcelServiceProvider::class,
],

// ...
'aliases' => [
    // ...
    'Excel' => 'Maatwebsite\Excel\Facades\Excel::class',
],
?>;

Publish your configuration

Last but not the least, run the vendor:publish command using artisan to publish your configuration:

php artisan vendor:publish -provider="Maatwebsite\Excel\ExcelServiceProvider"

Upon publishing, the config/excel.php configuration file will be created where you can make your changes.

Hope this helps you out!

View battery status

This comes in handy if you're using the terminal in full screen but still want to know your battery life. Just type the following:

upower -i /org/freedesktop/UPower/devices/battery_BAT0

Set up a new repository

Are you new to using Git? Then this is for you.

1. Set up a Git account

Go to GitHub and create your account with your email address.

2. Create a repository

Just create a new project with whatever you wanted. For this, you can just create git-starter-repo or something like that.

3. Initialize git in your project directory

Now, go to your project directory and initialize git by doing the following:

git init

4. Add your files

Add your files to the repository by doing the following:

git add .

Or if you want add selected files:

git add file_1 file_2

5. Commit your changes

Before you push your changes, you need to write a message about what changes are done:

git commit -m "this is my first commit"

6. Link your project to the repo

Do the following to link your project to the repo that you've created in step 1:

git remote add origin https://github.com/youraccount/repositoryname.git

7. Push changes

You can decide which branch you wanted to push but initially, you'll have one branch, which is called master:

git push -u origin master

Or if you have an existing branch, just replace master with yourbranchname.

Hope that helps you out!

Checkout branch

Want to create a new branch in your project? Simple, just do this:

git checkout -b new_branch

By doing this, you'll automatically be shifted to a new branch of your project. To check which branch you're working on, type this:

git branch

And you should be able to see your current branch marked with a *:

master
* new_branch

Writing a book on how to build ReactJS applications

I'm challenging myself to write a book on how to build simple applications using ReactJS

Over the past few months, I've been spending some of my free time to learn ReactJS and I've got to say, I really like it and got a hang of it after lots of trials and errors.

Just to make it clear, I didn't become a ReactJS expert or something but I figured that writing a book on something that you've learnt would help you understand the material much more deeper.

And since I do believe in it, I decided to challenge myself to write a book on it.

What's the aim of the book?

I aim to cover the fundamentals and concepts of ReactJS using a progressive and an example-driven approach. You know like on how to write reusable UI components, handle user events and interactions and managing state and props of a component.

By the end of this book, the reader will have solid understanding of React's concepts and be able to build cool applications using it.

When's it going to be released?

Honestly, I didn't plan on the size of the book yet but the practical content for it i.e. the actual code and applications are ready. I aim to release it somewhere around late April 2020.

Are you planning to monetize it?

Umm, nope! I believe that knowledge should be accessible for everyone and I plan on making the book open source, so that it can get updated as per the latest changes.

Conclusion

I know it's a short article but I feel like I wanted to challenge myself with a small goal for this year.

Let's see how it goes!

Using Laravel events and listeners in your application

Sharing my experiences of using events and listeners in my Laravel application.

Recently, I have started learning Laravel and now, I'm building an application for my new company using this amazing framework.

My senior developer was curious and thought of having a conversation with me that went like this:

Senior dev: Hmm, can I have a look at your code?

Me: Oh sure, here take a look.

Senior: (Goes through project file structure)

Senior: So, have you ever thought of using events in your application?

Me: Yeah, I wrote a custom JavaScript file to handle and fire events on the client-side like validating the forms and passing async requests to the server.

Senior: Hmm, that's okay but I'm talking using events in Laravel.

At this point, I was pretty clueless and I didn't know what the heck was going on. Events in PHP? I mean, I know about it in JavaScript because of it's event-driven architecture that we are all familiar with. But in PHP? I didn't know that.

Still confused, he proceeds to explain about it's concepts in an abstract manner and thanks to him, it induced my curiosity by asking myself: What's the deal in between using events over function calls using a route on a standard controller?

In today's article, I'll be talking about why and when to use events over function calls using Laravel in your application.

What's an event?

An event is a piece of reusable logic stored somewhere in your application that has a set of listeners waiting to be executed, if triggered.

Let's say, you have a simple CRUD application that involves user registration. Whenever a user registers, you may want to perform certain actions, such as:

  • Adding them into your mailing list
  • Confirmation of account

You can add more but this is just to give you an idea. Let's see take a look at two different approaches:

  1. Functional
  2. Events and Listeners

Functional

If you're using an MVC framework (Laravel, in our case), you'd do this in a controller with a bunch of methods like so:

<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\User;

class UserController extends Controller {
    public function index() {
        // insert code to view users page
    }

    public function create(Request $request) {
        $arr = [
            'username' => $request->username,
            'email' => $request->email,
            'password' => bcrypt('something')
        ];

        $user = User::create($arr);

        $this->sendConfirmationEmail($user);
        $this->subscribeToMailingList($user);
    }

    // Send confirmation email to user
    private function sendConfirmationEmail($user) {
        // insert code
    }

    // Subscribe user to mailing list
    private function subscribeToMailingList($user) {
        // insert code
    }
}
?>

This is approach is self-contained and simple to follow but you're also adding in a lot of responsibility to your controller.

Not only that, what if the user wants to register from another place in your application, in that case, you'll have to duplicate your logic in multiple places.

Events and Listeners

Using this approach, you can split this into Event and Listener files in your application.

<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\User;

class UserController extends Controller {
    public function index() {
        // insert code to view users page
    }

    public function create(Request $request) {
        $arr = [
            'username' => $request->username,
            'email' => $request->email,
            'password' => bcrypt('something')
        ];

        $user = User::create($arr);

        // Emit event
        event(new UserRegistered($user));
    }
}
?>

This is how your UserRegistered event would look like:

<?php
namespace App\Events;

use Illuminate\Queue\SerializeModels;
use App\User;

class UserRegistered {
    use SerializesModels;

    public $user;

    public function __construct(User $user) {
        $this->user = $user;
    }
}
?>

And this is how your SendConfirmationEmail listener would look like:

<?php
namespace App\Listeners;

use App\Events\UserRegistered;

class SendConfirmationEmail {

    public function __construct(User $user) {
        // insert code
    }

    public function handle(UserRegister $event) {
        // insert code
    }
}
?>

Using this approach, you can use the UserRegistered event anywhere you wanted in your application. No matter what happens, it will trigger the same actions as it was intended to do so. If you want to add a new functionality, create a new listener and register it with the event in your EventServiceProvider file like this:

<?php
protected $listen = [
    'App\Events\UserRegistered' => [
    'App\Listeners\SendConfirmationEmail',
    ],
];
?>

If you follow this approach, your logic complexity is toned down and the controller will have less responsibility.

Why use events and listeners over function calls?

Just like this answer that I found on StackOverflow question regarding events and listeners over calling functions:

You might not be in control of the code that's doing the calling. Or even if you are, you don't want to introduce dependencies into that code.

Think about it, what if you built an API or library that you want people to use but don't want them to modify the source code. Instead, you could provide a documentation that states specific events are raised under specific circumstances, in turn, they can write code that responds to such events.

I'm sure that there are more examples as to where this methodology might be applied.

When to use it?

Truth be told, it depends. If you have a simple application, then a functional approach is all you need but it's a larger and more complicated application, using Events and Listeners can be a better option.

Conclusion

Please note, I'm not an expert at this topic as I'm still learning and I thought of sharing what I had learnt. If you have any suggestions or thoughts, please share it with me on Twitter or send me a message to my inbox.

Hope you liked reading this article.

Stay tuned for more.

Extras

The Circle Packing Algorithm

Implemented a mathematically beautiful generative pattern that looks deceivingly complex to the human.

Beautiful, isn't it? It might look complex but it's mathematically quite impressive. Making this pattern wasn't hard but it definitely took a lot of trial and error to get it right and honestly, I don't really know if it's this is the most efficient way to generate this pattern.

This article isn't a tutorial but rather, I'll be talking about the algorithm itself. However, you can check out the source code in my GitHub repository.

How it works?

In order to achieve that "stacked" effect, there are two things to keep in mind:

  1. Generate circles with a random radius
  2. Look for collisions with other circles

The logic is quite similar to the Overlapping Rectangles problem except this is done with circles.

Generate circles with dynamic radius

This method will help generate valid circles with a random radius. Circles that don't overlap or collide with other circles are considered to be valid.

// Generate a valid circle
const generateCircle = () => {
    let newCircle;
    let isValidCircle = false;

    for(let i=0; i<attempts; i++) {
        newCircle = {
            x: Math.floor(Math.random() * width),
            y: Math.floor(Math.random() * width),
            radius: minRadius
        };

        if(checkForCollision(newCircle)) {
            continue;
        }
        else {
            isValidCircle = true;
            break;
        }
    }

    if(!isValidCircle) { return; }

    for(let i=minRadius; i<=maxRadius; i++) {
        newCircle.radius = i;
        if(checkForCollision(newCircle)) {
            newCircle.radius--;
            break;
        }
    }

    circles.push(newCircle);
    drawCircleOnCanvas(context, newCircle, colors[Math.floor(Math.random() * colors.length)]);
}

Look for collision with other circles

Thanks to some online research, I was able implement the Euclidean Distance equation that helped with calculating the distances between each circle and detect for collisions. Along with that, I also found another article on Touching Circles that was quite useful.

These are the formulas used to detect the collision:

  1. Find the distance between two centres \[ AB = \sqrt{ (x2 - x1)^2 - (y2 - y1)^2} \]

  2. Calculate the radii of both circles. \[R = r1 + r2\]

If the radii is greater than or equal to the euclidean distance of both circles, then it's a valid circle with no collisions.

// Check for collision in a canvas
const checkForCollision = (newCircle) => {

    let x2 = newCircle.x;
    let y2 = newCircle.y;
    let r2 = newCircle.radius;


    // Determine the euclidean distance between two circle
    // using Pythagorean Theorem.

    // Refer to: 
    // https://en.wikipedia.org/wiki/Euclidean_distance

    for(let i=0; i<circles.length; i++) {

        let otherCircle = circles[i];
        let r1 = otherCircle.radius;
        let x1 = otherCircle.x;
        let y1 = otherCircle.y;
        let xx = ((x2 - x1) * (x2 - x1));
        let yy = ((y2 - y1) * (y2 - y1));
        let radii = r2 + r1;
        let euclidDistance = Math.sqrt(xx + yy);

        if(radii >= euclidDistance) {
            return true;
        }
    }

    // Check collision on top
    if(x2 + r2 >= width || 
        x2 - r2 <= 0) {
        return true;
    }

    // Check collision on bottom
    if(y2 + r2 >= width || 
        y2 - r2 <= 0) {
        return true;
    }

    //else return false
    return false;
}

Conclusion

I'm thinking of implementing more generative patterns like Triangular Mesh and Piet Mondrian's Red, Blue and Yellow composition.

Hope you liked reading this article.

Stay tuned for more!

Deploy your Laravel app on Heroku

Learn how to deploy your Laravel application along with a database on Heroku.

In my previous article, I talked about how to setup your environment for developing your Laravel applications. Today, I'll be talking about deploying your application along with a database on Heroku.

I wrote a simple CRUD application using Laravel but didn't understand on how to host it. I tried to host it on free shared hosting service but apparently, most of them don't support PHP system calls like proc_open(). However, if it was a VPS hosting service, it's supported but ain't nobody got time for shelling out cash for a test drive.

As an alternative, I went on google and discovered that Heroku does support my requirements and it worked flawlessly, which is why I thought of sharing this information to others as well.

If you're a developer who's at the early stages of learning Laravel (like me 😆), then this article is for you.

Prerequisites

You'll be doing some minor configurations, so you should be fine as long as you have a stable internet connection, familiar with using the CLI (Command Line Interface) and have some PHP knowledge.

If you're a Windows user, please Git for Windows. Else, if you're a Linux or macOS user, you should be fine.

How to deploy?

You can ignore the first two steps if you already know about Heroku and how to work with it but please follow the rest of the steps:

  1. Install Heroku
  2. Create a Heroku repository
  3. Define Procfile
  4. Push Laravel app to repository
  5. Add configuration variables
  6. Setup your database

Install Heroku CLI

You can install this directly from the command line by typing the following:

sudo snap install heroku --classic

Create a Heroku repository

If you don't have a Heroku account yet, create an account now and once you're done with that, type the following:

heroku login

Follow the login instructions from the command line prompt, fill in your login credentials and you'll be in!

Once, you're done with that, create a repository by doing the following:

heroku create

In a few seconds, you'll get a randomly generated domain address, which is the link to your Heroku repository. If you can't remember the link, it's fine, you can make changes to it in your Heroku account.

Define Procfile

In case, you don't know what's a Procfile, it's a file that specifies the commands that needs to be executed by the application on startup. You can declare a variety of process types, click here to learn more.

Since our application is PHP based, we need to add some specific command that selects the server on boot, I chose Apache server for this project:

cd your_laravel_project
touch Procfile
echo "web: vendor/bin/heroku-php-apache2 web/" > Procfile

Push Laravel app to repository

It's similar to pushing your code into your GitHub, except this time, it's your Heroku repository. Type the following in your command line:

git add .
git commit -m "pushing application to repo"
git push heroku master

To check if your application is launched, type the following:

heroku open

At this stage, you might face Error 500, that's normal because we'll take care of that in the next step.

Configure your Heroku environment

We need to add some config variables that changes the way your app behaves. So, let's start adding it:

heroku config:set APP_DEBUG=true
heroku config:set APP_KEY=yourlaravelapplicationkey
heroku config:set APP_URL=https://yourwebsite.herokuapp.com
heroku config:set REDIRECT_HTTPS=true

In this configuration, you have done the following: - Enabled debug mode - Set your Laravel application's base64 encrypted key - The website's URL - Force HTTPS redirect (Useful, when you're calling external assets that uses HTTPS protocol)

Note: You can find your APP_KEY in your .env file that's found in your project directory.

Setup your database

Initially, I built the database on MySQL but I later learnt that Heroku gives a free PostgreSQL starter database. I've never tried PostgreSQL before but it's quite similar to MySQL, so you shouldn't worry about your schema as Laravel supports PostgreSQL and MySQL databases by default.

Type the following in the command line:

heroku addons:create heroku-postgresql:hobby-dev

This will create a PostgreSQL database and sets a DATABASE_URL, which contains the username and password to the database. To check it, type the following:

heroku config

Now, go to your project directory and open the config/database.php file and add the following:

<?php
// Place these variables above
$url = parse_url(getenv("DATABASE_URL"));
$host = $url["host"]??null;
$username = $url["user"]??null;
$password = $url["pass"]??null;
$database = substr($url["path"], 1)??null;

// Replace the default connection
'default' => env('DB_CONNECTION', 'pgsql_prod'),

// Under the connections attribute, create a new connection called 'pgsql_prod'
'pgsql_production' => [
    'driver' => 'pgsql',
    'host' => $host,
    'database' => $database,
    'username' => $username,
    'password' => $password,
    'charset' => 'utf-8',
    'prefix' => '',
    'schema' => 'public',
],
?>

Push the new changes to your repository:

git add .
git commit -m "configured database"
git push heroku master

One last step, we need to create the tables from your schema, so type the following:

heroku run php /app/artisan migrate --seed

Follow the command line prompt and voila, you have successfully deployed your Laravel application with a database on Heroku.

Conclusion

Well, I hope you found this article really useful especially if you're a beginner. If you do find this useful, please share it with others too!

Stay tuned for more!