Krishnamoorthy Acharya
Krishnamoorthy Acharya

Reputation: 4254

Laravel creating API return with help of JSON field in MySQL

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);

Upvotes: 0

Views: 838

Answers (1)

Ahmad Elkenany
Ahmad Elkenany

Reputation: 585

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

Upvotes: 1

Related Questions