Abdul Rehman
Abdul Rehman

Reputation: 25

Laravel how to modify the returned result from eloquent to convert json string to json object

Description and welcomeEmailContents are type text in db ,and both store same type data . Description return json obj while issue is welcomeEmailContents return string.

$course_desc_blocks = ($courseData['description'] != null) ? json_encode($courseData['description']) : null;
$course_welcome_blocks = ($courseData['welcomeEmailContents'] != null) ? json_encode($courseData['welcomeEmailContents']) : null;
    
//Laravel Query:-
 $courseData = Course::select('id', 'title', 'description','welcomeEmailContents', 'price', 'site_id', 'status', 'expiry_days')->orderBy('id', 'asc'));
return response()->json( $courseData );
//===================================== 
//output
{
  "data": {
    "id": 100,
    "title": "Python",
    "description": [
      {
        "type": "paragraph",
        "data": {
          "text": "jsonTesting"
        }
      }
    ],
    "welcomeEmailContents": "[{\"type\":\"paragraph\",\"data\":{\"text\":\"Testingjson\"}}]",
    "price": 0
  }
  
}

Upvotes: 0

Views: 843

Answers (1)

Roj Vroemen
Roj Vroemen

Reputation: 1892

The easiest way to accomplish this would be to add a json cast to the welcomeEmailContents field.

class Course extends Model
{
    protected $casts = [
        'welcomeEmailContents' => 'json',
    ];
}

Please note that with the snippet above you no longer have to manually encode the json when setting the field but instead just set it as an array.

Course::create([
    // Some more fields...
    'welcomeEmailContents' => [
        [
            'type' => 'paragraph',
            'data' => [
                'text' => 'testingjson',
            ],
        ],
    ],
]);

There are multiple ways to accomplish the above. You can find more info on this in the documentation: https://laravel.com/docs/8.x/eloquent-mutators

Upvotes: 2

Related Questions