Member-only story

Using MySQL SET Columns in Laravel

Yoram Kornatzky
Dec 14, 2024

--

MySQL SET column

A set column in the Laravel framework stores a set of values that come from some predefined enumerated set. It stands for a MySQL SET column. Surprisingly, the column should be treated as a string in your PHP code.

The Migration

public function up(): void
{
Schema::table('auctions', function (Blueprint $table) {
$table->set('activities', ['focus', 'webinar', 'conference', 'presentation', 'video_call', 'screening'])->nullable();
});
}

The initial value for the column is NULL.

Setting a Value

Treat the current value of the column as a string and concatenate an additional element:

$auction = Auction::find(10);
$auction->activities = $auction->activities . ',' . 'conference';

Does It Contain a Value

To check if the column contains a particular value, use string containment. So for the Auction model, define the attribute is_webinar as:

public function getIsWebinarAttribute()
{
return Str::contains($this->activities, 'webinar');
}

--

--

Yoram Kornatzky
Yoram Kornatzky

Written by Yoram Kornatzky

Entrepreneur, Auctibles: https://auctibles.com, 25 years of development experience, Ph.D. Computer Science

No responses yet