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();
});
👋 Hi there! This is Amit, again. I write articles about all things web development. If you enjoy my work (the articles, the open-source projects, my general demeanour... anything really), consider leaving a tip & supporting the site. Your support is incredibly appreciated!