0

I have a requirement wherein I will be creating a JSON response. This will be active only for a day. So simply to avoid the creating JSON response I can store it in the MySQL Database. The issue is I am able to create JSON response, Save it in MySQL JSON field. However, I am not able to return a response directly via MySQL field.

//getting the value's from db
 $news = DB::table('news')->where('news_item_name', $news_id)->first();
// checking if the news json values are still active(Cron job will delete expired news articles)
if (isset($news->news_expiry)) {
    //this part is not working
    return response()->json($news->news_content);
}
//if no news exits create new JSON and save it in the database.
$array = [];
$array[0]['title'] = "some news";
$array[0]['link'] = "http://www.example.com/";
$array[0]['source'] = "example.com ";
$array[0]['description'] = "some news description";
$array[0]['thumbnail']="http://www.example.com/images/sample.png";

//insert fresh news json with an expiry time.
 DB::table('news')->insert(
            ['news_item_name' => $news_id, 'news_content' => json_encode($array), 'news_expiry' => some_expiry_time]
    );
    return response()->json($array);

1 Answer 1

1

If this only the case you can use this:

//insert of news json with an expiry time.
 $saved = DB::table('news')->insert([
          'news_item_name' => $news_id, 
          'news_content' => json_encode($array), 'news_expiry' => some_expiry_time
        ]);
return response()->json($saved->news_content);

But if it possible to change to Elequent and use Laravel getter and setter in model you can do that:

to set a value before inserting

public function setNewsContentAttribute($value)
{
   $this->attributes['news_content'] = json_encode($value);
}

to fetch the value

public function getNewsContentAttribute()
{
    return json_decode($this->news_content);
} 

check laravel docs for elequent

Sign up to request clarification or add additional context in comments.

1 Comment

this issue got resolved with following "return response()->json(json_decode($news->news_content,true)); " .I missed to decode the encoded values

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.