Blog

Auto unserialize column while fetching the model, only if it contains serialized array – Laravel 7/8

Share your learning

Hey buddy, yesterday I tried to auto unserialize a column if it contains the serialized array in Laravel. But the issue was that sometimes it contains plain text not the serialized array.

I was using the laravel eloquent accessor to auto unserialize the column value. Like below

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class ExampleMeta extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */    protected $fillable = [
       'name', 'meta_key', 'meta_value'
    ];

    public function getMetaValueAttribute($value)
    {
        return unserialize($value);
    }
}

But the issue was it started to throw an error when the column contains plain string not the serialized array. 

After some research I found the solution as below.

public function getMetaValueAttribute($value)  {
   return @unserialize($value) !== false ? unserialize($value) : $value;
}

Now, it will auto unserialize column value only if it contains the serialized array otherwise will return the same value.

If you have any query plz let me know in the comment below.

Satpal

Recent Posts

How to Switch PHP Versions in XAMPP Easily: Managing Multiple PHP Versions on Ubuntu

Today we are going to learn about managing multiple PHP versions on ubuntu with xampp.…

1 year ago

How to Use Coding to Improve Your Website’s SEO Ranking?

Let's understand about how to use coding to improve your website's SEO. In today’s computerized…

1 year ago

Most Important Linux Commands for Web Developers

Let's understand the most important linux commands for web developers. Linux, as an open-source and…

1 year ago

Top 75+ Laravel Interview Questions Asked by Top MNCs

Today we are going to discuss top 75+ Laravel interview questions asked by top MNCs.Laravel,…

1 year ago

Mailtrap Integration for Email Testing with Laravel 10

Today we will discuss about the Mailtrap integration with laravel 10 .Sending and receiving emails…

1 year ago

Firebase Cloud Messaging (FCM) with Ionic 6: Push Notifications

Today we are going to integrate FCM (Firebase Cloud Messaging) push notifications with ionic application.Firebase…

1 year ago