Laravel Tricks: Turning Database Strings into Arrays

How to get string data as array from DB in Laravel

How to get string data as array from DB in Laravel


In this article we will learn how to convert string data to array in Laravel . We will take an example where we will retrieve column data from Database in the format of array which is initially stored in the form of string or text by the use of attribute casting .

Laravel provides us attribute casting by which we can convert our attribute type while fetching data from DB without writing any additional methods on our model . We just have to define the " $casts " property which should be an array , the key of this array should be the column name of your respected table and the value should be the casting type .

Quick Solution :

Simple define the $cast method in your model , with the column name as shown below .

protected $casts = [
        'days' => 'array'
    ];

Example :

We will take an example where we will fetch record from users table where we have stored name of 7 days in string format in days column and then by using $casts property we will convert it to array .

How to get string data as array from DB in Laravel

UserController.php :

public function stringToArray()
    {
      $user_days = User::find(1);
      return $user_days;
    }

Write the following code on your model of your table connected .

User.php :

protected $casts = [
        'days' => 'array'
    ];

Output without casting :

How to get string data as array from DB in Laravel


Output after casting :

How to get string data as array from DB in Laravel


In this way you can cast your attributes of your DB . We only seen how can you cast a string type to array but there are also lots of cast types you can use as shown below .

  • array
  • boolean
  • collection
  • date
  • datetime
  • decimal:<digits>
  • double
  • encrypted
  • encrypted:array
  • encrypted:collection
  • encrypted:object
  • float
  • integer
  • object
  • real
  • string
  • timestamp
You can visit the Laravel's offical site to get more information about Mutator and Casting .


Previous Post Next Post

Contact Form