In some cases, you may want to store multiple values in a single column in MySQL using Laravel. For instance, you may want to store a list of tags pertaining to a blog post in a single column. This tutorial will guide you on how to do this using the Laravel framework.
Steps
Step 1: Create Migration
First, we need to create a migration using Artisan CLI, Laravel’s command-line interface. This migration will create the table that will store your data. Run the following command:
1 |
php artisan make:migration create_posts_table --create=posts |
The above command will create a migration file named create_posts_table.
Step 2: Define Columns
Open the migration file in your chosen code editor and define columns. For instance, if you want to store multiple tags for a blog post, add a column named ‘tags’ to the migration file.
1 2 3 4 5 6 7 |
Schema::create('posts', function (Blueprint $table) { $table->id(); $table->string('title'); $table->text('content'); $table->string('tags'); $table->timestamps(); }); |
Step 3: Store multiple values in the tags column
In this step, we are going to store multiple values in the ‘tags’ column. To achieve this, we will serialize an array of tags, and then store it in the column.
In your model, you should define a setter and a getter for the ‘tags’ attribute.
1 2 3 4 5 6 7 8 9 |
public function setTagsAttribute($value) { $this->attributes['tags'] = serialize($value); } public function getTagsAttribute($value) { return unserialize($value); } |
Once the setter and the getter functions have been defined, you can assign an array of tags to the tags property of the blog post instance.
1 2 3 4 5 |
$post = new Post; $post->title = 'Laravel Blog Post'; $post->content = 'Lorem ipsum dolor sit amet'; $post->tags = ['laravel', 'php', 'webdev']; $post->save(); |
Step 4: Display the tags
To display the tags, you can use the ‘tags’ property of the blog post instance.
1 2 3 4 5 |
<ul> @foreach ($post->tags as $tag) <li>{{ $tag }}</li> @endforeach </ul> |
Conclusion
This method allows you to store multiple values in a single MySQL column using Laravel. It is useful when you want to store related data in one column.
Here is the full code for the Post model:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class Post extends Model { protected $fillable = ['title', 'content', 'tags']; public function setTagsAttribute($value) { $this->attributes['tags'] = serialize($value); } public function getTagsAttribute($value) { return unserialize($value); } } |
Here is the full code for the posts table migration:
1 2 3 4 5 6 7 |
Schema::create('posts', function (Blueprint $table) { $table->id(); $table->string('title'); $table->text('content'); $table->string('tags'); $table->timestamps(); }); |
And that’s it!