How to get string data as object from DB in Laravel
In this article we will learn how to convert string data to object 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 object , 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' => 'object' ];
Example :
We will take an example where we will fetch record from users table where i have stored some data in the format of object as you can see in the screenshot .
{ "sun": { "time_tracking": false, "user_authentication": true }, "mon": { "time_tracking": true, "user_authentication": true }, "tue": { "time_tracking": true, "user_authentication": true }, "wed": { "time_tracking": true, "user_authentication": true } }
UserController.php :
public function stringToObject() { $user_days = User::find(1); return $user_days; }
Write the following code on your model of your table connected .
User.php :
protected $casts = [ 'days' => 'object' ];
Output without casting :
In this way you can cast your attributes of your DB . We only seen how can you cast a string type to object 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 .
Thank you for reading this article 😊
For any query do not hesitate to comment 💬