Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Invisible MySQL columns in Laravel 8.x

Let’s imagine a scenario where you have a MySQL table called users and there’s a column called secret which holds a secret token for the associated users.

How would you prevent this column from not being there when someone queries everything (i.e SELECT * query) from this table? Well, one way is to explicitly specify each column in the SELECT query except the secret column.

What are invisible columns?

Or if you’re using MySQL 8.0.23 and onwards, you could define the secret column as “invisible”. An invisible column is normally hidden to queries but can be accessed if explicitly referenced. Before MySQL 8.0.23, all columns are visible.

Here’s how you can define a column as invisible when creating a table.

CREATE TABLE users (
  id INT,
  secret TINYTEXT INVISIBLE
) ENGINE = InnoDB;

Or when you’re altering the table.

ALTER TABLE users ADD COLUMN secret TINYTEXT INVISIBLE;

This is how a column can be made “invisible”. So, that it would be hidden from the SELECT * queries unless explicitly referenced!

Invisible columns in Laravel

The provision to define a column as invisible wasn’t there in the Laravel schema until the recent release of Laravel 8.x

Now, it’s possible by using a new invisible() method on the table Blueprint like so.

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

Schema::table('users', function (Blueprint $table) {
    $table->string('secret')->nullable()->invisible();
});
Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?