megacolorboy

Abdush Shakoor's Weblog

Writings, experiments & ideas.

How to exclude certain slugs in Laravel

Using plain Regular Expressions, you can exclude certain slug from your routes, try adding the following to your routes/web.php file:

<?php
    Route::match(array('GET', 'POST'), '/{slug}', 'YourController@index')->name('page')->where('slug', '^(?!pattern).*$');
?>

Hope you found this useful!

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!

Clearing cache on a Shared Hosting Server

Hosted your website on a Shared Hosting Server and got limited access to clear the cache on your project?

Open up routes/web.php and create this route:

<?php
Route::get('/clearcache', function(){
    \Artisan::run('config:clear');
    \Artisan::run('cache:clear');
    \Artisan::run('view:clear');
    \Artisan::run('route:clear');
    \Artisan::run('config:cache');
});
?>

Just type the URL and it will clear all existing cache from the project.

Hope this helps you out!

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!

Use MySQL 8.0 with Native Password Authentication

Last month, I was configuring an Ubuntu Server to deploy a client's project that uses MySQL 8.0 and PHP 7.2. So, I installed the necessary dependencies and finally installed MySQL 8.0, created a new schema and imported the database tables required for the project.

Next, I typed the project URL and ran into this error:

Unable to load plugin 'caching_sha2_password'

If you're running PHP 7.2 and facing this error, you should know that PHP 7.2 doesn't support native password authentication by default. But it's a simple fix, all you have to do is either one of the following:

  1. Alter the current user's authentication to native password
  2. Create a new user with native password authentication

Alter the current user's authentication to native password

ALTER USER 'your_user'@'your_server_host' IDENTIFIED WITH mysql_native_password BY 'your_password';

Create a new user with native password authentication

CREATE USER 'your_user'@'your_server_host ' IDENTIFIED WITH mysql_native_password BY 'your_password'

For the changes to take effect, you need to reload the privileges by typing the following:

FLUSH PRIVILEGES;

Hope this helps you out!

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!.

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!

Resolve the "General error: 1835 Malformed communication packet" error

This happened like two days ago, when one of the client sites went down. Upon inspecting the error logs, I found this:

SQLSTATE[HY000]: General error: 1835 Malformed communication packet

If you got the same error as the one above, don't worry, it's not your fault. According to this forum, a recent MariaDB update introduced a new bug for PHP versions < 7.3 that uses PDO and MySQL connectors. You can easily resolve this by simply upgrading it to PHP 7.3.

Hope this tip helps you out!