megacolorboy

Abdush Shakoor's Weblog

Writings, experiments & ideas.

Convert to date from timestamp using Carbon

Using Carbon's createFromFormat() method is basically a wrapper for DateTime::createFromFormat(), the main difference between the two methods is that you can add a timezone to Carbon's method.

Here's a sample on how you can convert to date using timestamp using Carbon:

<?php
    function formatDate(Request $request) {
        return \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $request->date)->format('Y-m-d');
    }
?>

Hope you found this useful!

Convert string to date using MySQL

Today, I was debugging a piece of code that is supposed to return a list of data based on the year, the funny thing is that the data was being returned on the development server but not on the production one.

Weird, so I opened up MySQL Workbench and wrote a simple query to see if the dates were being returned because who knows maybe they weren't stored at all.

SELECT YEAR(date_posted) FROM posts;

The values returned were null. Now, that's strange because the dates were present in the column. So, I took a deep look and figured out that the dates were stored in VARCHAR instead of DATETIME data type! 😔

Luckily, I figured that there's a way to resolve this by STR_TO_DATE() function:

SELECT YEAR(STR_TO_DATE(date_posted, '%Y-%m-%d')) FROM posts;

Bam! The results were coming now! 😌

Hope this helps you out!

Show Git branch in your Bash prompt (with colors)

Do you work on a project with multiple Git branches but don't know which one you're in? Open your .bashrc file and add this:

force_color_prompt=yes
color_prompt=yes

parse_git_branch() {
 git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}

if [ "$color_prompt" = yes ]; then
 PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[01;31m\]$(parse_git_branch)\[\033[00m\]\$ '
else
 PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w$(parse_git_branch)\$ '
fi

unset color_prompt force_color_prompt

Updated: November 26th, 2022

The above script works fine for Ubuntu but doesn't work fine on other distros. Here's an alternative one that works on all distros:
parse_git_branch() {
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}

export PS1="\u@\h \[\e[32m\]\w \[\e[91m\]\$(parse_git_branch)\[\e[00m\]$ "

Save the file and execute this command for your changes to take effect:

source ~/.bashrc

Now, you should see your colors in your Bash prompt along with the Git branch that you're working on (Note: this will be shown if you're in a project that uses a Git repository).

Hope this helps you out!

How to resolve the "file_get_contents(): SSL operation failed" error

If you're facing this error while trying to download a file from your server, it's most probably the SSL certificate that has been hosted on your server isn't correctly verified or maybe, you're using OpenSSL on a server running PHP 5.6.

As per the documentation, there are some changes that can be made to resolve it, like the following method:

<?php
public function foo(Request $request) {
    $arrContextOptions = array(
        "ssl" => array(
            "verify_peer" => false,
            "verify_peer_name" => false,
        ),
    );
    return Response::make(file_get_contents(asset('pdf/file.pdf'), false, stream_context_create($arrContextOptions)), 200, [
        'Content-Type' => 'application/pdf',
        'Content-Disposition' => 'inline; filename="file.pdf"',
    ]);
}
?>

Although, I won't recommend this unless you are testing it on a localhost environment as it's not secure and could have significant security implications because disabling verification can permit a Man in the Middle attack to take place.

Use it at your own risk!

Check if trait is being used in your class

Want to know if a trait is being used in your current class? Try this:

<?php
in_array(Foo::class, class_uses($this))
?>

By any chance, if the current class is inherited, please note that the class_uses() method will only return the list of traits used by the current class and won't include any traits of it's parent class.

Create migrations and seeds from an existing database

Up until now, I've written migrations and generated seeders for some Laravel projects that I have worked on but recently, I thought of seeing if there's a way to generate migrations and seeds from an existing database especially if it's a project that never had any migrations or seeds created before.

Luckily, I found these two packages, which turned out to be quite productive:

  1. kitloong/laravel-migrations-generator
  2. orangehill/iseed

Execute the following commands to install the packages mentioned above:

composer require --dev "kitloong/laravel-migrations-generator"
composer require orangehill/iseed

Generate migrations using existing database

You can generate your migrations for all tables like this:

php artisan migrate:generate

Or, you can specify the tables you wish to generate:

php artisan migrate:generate table1,table2,table3

Generate new seeds using existing database

You can generate seeds for a single table like this:

php artisan iseed table_name

And for multiple tables, you can do this:

php artisan iseed table1,table2,table3

Hope you find this tip useful!.

How to resolve the issue of not receiving emails on the same domain?

Recently, we hosted our company's redesigned website on GoDaddy, which offers cPanel to manage your website. I was dealing with an annoying email bug in which I was able to send/receive emails to any account except the ones that share the company domain.

The company's current email setup makes use of Google Workspace and since we're using a Shared Hosting account, GoDaddy allows you to use their SMTP relay and prohibits the use of third-party SMTP services such as Google Workspace, Outlook, etc.

After configuring it with Google's MX records in the DNS settings, I wasn't receiving any email on my own company email yet I was able to receive on other email accounts that didn't share the company's domain.

I did a little R&D and ran into this documentation about email routing and figured out that there could be an issue with it's configuration.

Here's what I did:

  1. Open cPanel
  2. Search or look for Email Routing
  3. Click on Email Routing
  4. If your MX records are not pointing to the IP address of the hosting server, then select Remote Mail Exchanger
  5. Save changes

After following these steps, I was able to receive mails on the same domain!

So what really caused the issue?

Since, we didn't have a default email address set up in cPanel, the current mode to send all unrouted emails was set to :blackhole:, by default. I guess, it's set up that way to prevent the server from sending/receiving spam mails from the domain.

This makes sense because:

  1. The MX records are not pointing to the current server
  2. There are no email accounts created for the domain on cPanel
  3. By setting the mode to :blackhole, all emails with the same domain are being discarded or rejected

Not really sure if this is what caused the issue but judging from the facts, I was able to reach to this conclusion.

Hope you found this tip useful.

Reference

Convert string from snake case to camel case

Thought of sharing a simple regular expression that I use on VIM to convert snake_case letters to camelCase letters (see what I did there) 😜

Here's the pattern for you to use:

:s/ \([a-zA-Z]\)/\u\1/g

Hope you found this tip useful!