PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, April 18, 2022

[FIXED] How to return json response in Laravel using eloquent without \r\n

 April 18, 2022     json, laravel, lumen, php     No comments   

Issue

I'm using laravel with eloquent and in json response i get \r\n. How can i get rid of them?

public function showOneProduct($lng)
{
  return response()->json(Product::where('language', $lng)->get());
}

response:

[
    {
        "id_produs": 1,
        "produs": " [\r\n        {\r\n        \"product_line\": \"TankTorq Line\",\r\n        \"colors\": [\r\n           \"#D66732\",\r\n           \"#000000\",\r\n           \"#909090\",\r\n           \"#E0E0E0\"\r\n        ],\r\n        \"max_speed\": \"46 km/h\",\r\n        \"range\": \"up to 40 km\",\r\n        \"weight\": \"13.2 kg\",\r\n        \"engine\": \"700W\",\r\n        \"nominalPower\": \"700W\",\r\n        \"nominalContinuousPower\": \"500W\",\r\n        \"line_image\": \"https://worldconnect.me/images/tanktork.png\",\r\n        \"products\": [\r\n           {\r\n              \"name\": \"TK2\",\r\n              \"scooter_features\": [\r\n                 {\r\n                    \"title\": \"Dual motor technology\",\r\n ]",
        "language": "en"
    }
]

Solution

you are saving the produs column as JSON, so you can use accessor to retrieve it as an array instead of JSON

public function getProdusAttribute($value) {
  return json_decode($value,true);
}

in case you still want to retrieve as it its with just removing \r\n you can use preg_replace , it will do the trick

   public function getProdusAttribute($value) {
      return preg_replace("!\r?\n!", "", $value);
    }


Answered By - Omar Tammam
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing