LaraBABA's avatar

Having issue with json data saved in DB that needs to go back to vue js

Hi all,

I am having an issue.

I am saving an article in my db as(I encode the main article json part):

$jsonEncode = json_encode($request->article);
 $article = Article::Create([
            'title' => $request->topic,
            'article' => $jsonEncode,
            'language' => $request->language,
            'user_id' => Auth::id(),
            'saved' => 1, ]);
"[{\"id\":1,\"title\":\"Types of products that can be sold online\",\"paragraph\":\"When it comes to shopping, many people prefer to do so online. There are a variety of reasons for this: convenience, price comparison, and selection. Here are some types of products that can be sold online: \n\n1. Clothing and accessories: Whether you're looking for something new to wear or just need a few new pieces of jewelry, you can find them all online. Plus, there's no need to leave the comfort of your home! \n\n2. Home goods: From towels and sheets to furniture and appliances, you can find everything you need to furnish your home without ever leaving the comfort of your own couch or bed. Plus, with prices often being lower than in stores, why not shop around before making a purchase? \n\n3. Food: If you're looking for something special in the way of cuisine (or just want to save money), look no further than the internet! You can find everything from international recipes to quick and easy meal ideas. And don't forget about those hard-to-find ingredients - they're often much cheaper online than in stores!\"},{\"id\":2,\"title\":\"Benefits of selling products online\",\"paragraph\":\"There are many benefits to selling products online, including the ability to reach a wider audience than you would if selling through brick-and-mortar stores. Additionally, online sellers can often keep more of the profits from their sales since there is no need for overhead costs like rent or staff salaries. Finally, buyers can purchase products from anywhere in the world, making it an ideal way to sell products to customers who may not be able to visit your store.\"},{\"id\":3,\"title\":\"The different types of marketing techniques that can be used to sell products online\",\"paragraph\":\"There are many different marketing techniques that can be used to sell products online. Some of the most common methods include email marketing, social media marketing, and online advertising. Each of these methods has its own strengths and weaknesses, so it's important to choose the right one for your product and target audience.\n\nEmail Marketing\nEmail marketing is probably the most common type of marketing online. It's simple to set up and use, and it can be very effective at reaching a wide audience. Email campaigns can be targeted based on location, age, or interests, which makes them versatile tools for businesses of all sizes.\n\nOne downside of email marketing is that it can be difficult to track results. This is because email addresses are often anonymous (or at least not easily traceable). If you're looking for detailed feedback on your campaign performance, email marketing may not be the best option.\n\nSocial Media Marketing\nSocial media platforms like Facebook and Twitter are great ways to connect with potential customers directly. They're also great channels for promoting your products and services. Social media platforms are especially useful for small businesses that don't have a lot of money to spend on advertising campaigns.\n\nOne downside of social media marketing is that it can be time-consuming (and sometimes expensive) to maintain a strong presence on these platforms.\"},{\"id\":4,\"title\":\"Tips for setting up an effective online store\",\"paragraph\":\"Setting up an online store can be a daunting task, but with a little preparation and some helpful tips, it can be a successful venture. Here are five tips for setting up an effective online store:\n\n1. Choose the right platform. There are many different platforms available to set up an online store, and it is important to choose the one that will best suit your needs. Some popular options include Shopify, WordPress, and Drupal. Each has its own strengths and weaknesses, so it is important to decide which one will work best for your business before starting construction.\n\n2. Plan your layout carefully. Once you have chosen a platform, the next step is to plan your layout. Make sure all of your content is easily accessible from the home page and that all of your products are organized in logical categories. You also want to make sure that you have enough space to display pictures and product information.\n\n3. Build a strong branding strategy. One of the most important aspects of setting up an online store is creating a strong branding strategy. Make sure all of your content (including product descriptions, images, and pricing) reflects the image you want to project for your business. Also consider developing marketing materials (such as flyers or web ads) that target specific demographics or interests related to your products.\n\n4. Get organized early on In order to run an effective online store, you need to get organized from the start. Set up standard shipping procedures and create labels for each product so that customers know exactly what they're paying for when they checkout\u3002 Also make sure you have automated systems in place (such as order tracking software) so you can keep track of inventory levels and customer activity\u3002 Finally, keep accurate records of all sales data so you can measure progress over time and make necessary adjustments\u3002\n\n5 . Stay focused on customer needs In order to keep customers coming back again and again, it is essential that you focus on their needs first and foremost\u3002 Make sure all of your content (including product descriptions, images, pricing information, etc.\"},{\"id\":5,\"title\":\"How to create a successful ecommerce website\",\"paragraph\":\"Creating a successful ecommerce website is not as difficult as one might think. There are a few key things that need to be in place for any website to be successful, and these include: an effective search engine optimization strategy, effective marketing techniques, and an attractive design.\n\nOne of the most important aspects of any ecommerce website is its search engine optimization (SEO). A well-optimized website will rank higher on search engines results pages (SERPs), which will lead to increased traffic and sales. There are a number of different SEO techniques that can be used to achieve this, including keyword research, on-page optimization, and link building.\n\nEffective marketing also plays a major role in the success of any ecommerce website. It is essential that the site has a clear mission statement and target market, as well as clear product descriptions and images. Additionally, regular blog posts should be written about new products or upcoming sales events, in order to keep customers informed about what\u2019s happening with the business.\n\nFinally, it\u2019s important to have an attractive design if the goal is to attract more visitors and customers. A well-designed site will look professional and sleek \u2013 making it easier for potential buyers to find information they\u2019re looking for and making the purchase process more enjoyable overall.\"},{\"id\":6,\"title\":\"The importance of social media when selling products online\",\"paragraph\":\"When selling products online, social media is an important tool. Social media allows customers and potential customers to connect with the business in a way that was never possible before. It also allows businesses to interact with their customers in a more personal way than ever before. This interaction can help build trust and credibility between the business and its customer base. Additionally, social media can be used to promote the product directly to potential customers. This can help increase sales by reaching new buyers who may not have otherwise known about the product. Overall, social media is an essential part of any online sales strategy.\"},{\"id\":7,\"title\":\"The top mistakes made by ecommerce entrepreneurs\",\"paragraph\":\"1. Not setting realistic expectations for their business. Many entrepreneurs assume that starting an online store is as easy as filling out a few forms and uploading some pictures, when in reality it takes a lot of hard work and dedication to succeed. Before starting your own ecommerce business, make sure you understand what it will take to achieve success and set reasonable goals for yourself.\n\n2. Focusing too much on the wrong metrics. It\u2019s important to be aware of your business\u2019s key performance indicators (KPIs), but don\u2019t let them drive your decisions more than anything else. Instead, focus on making your store as successful as possible based on customer satisfaction and retention rates rather than raw numbers alone.\n\n3. Making poor choices with their marketing strategy. Once your store is up and running, make sure you invest in effective marketing campaigns that will bring in new customers. However, don\u2019t forget to keep track of your spending so you can stay within budget \u2013 overspending on marketing can lead to disastrous results down the line!\n\n4. Ignoring the importance of customer service . No matter how good your product or service may be, if customers have trouble using it or finding what they need, they\u2019re likely going to leave negative reviews online or even stop shopping at all. Make sure you have a solid customer service plan in place that can handle any issues that arise \u2013 no matter how small they may seem at first glance!\"}]"

When I request this db data via eloquent as:

    public function editArticle(Request $request)
    {
        $output = Article::where('user_id', Auth::id())->where('id', '=', $request->id)->first();

        return response()->json(['r' => $output], 200);
    }

I am getting thisd output:

{
    "id": 140,
    "user_id": 376,
    "article": "\"[{\\"id\\":1,\\"title\\":\\"Types of products that can be sold online\\",\\"paragraph\\":\\"When it comes to shopping, many people prefer to do so online. There are a variety of reasons for this: convenience, price comparison, and selection. Here are some types of products that can be sold online: \\n\\n1. Clothing and accessories: Whether you're looking for something new to wear or just need a few new pieces of jewelry, you can find them all online. Plus, there's no need to leave the comfort of your home! \\n\\n2. Home goods: From towels and sheets to furniture and appliances, you can find everything you need to furnish your home without ever leaving the comfort of your own couch or bed. Plus, with prices often being lower than in stores, why not shop around before making a purchase? \\n\\n3. Food: If you're looking for something special in the way of cuisine (or just want to save money), look no further than the internet! You can find everything from international recipes to quick and easy meal ideas. And don't forget about those hard-to-find ingredients - they're often much cheaper online than in stores!\\"},{\\"id\\":2,\\"title\\":\\"Benefits of selling products online\\",\\"paragraph\\":\\"There are many benefits to selling products online, including the ability to reach a wider audience than you would if selling through brick-and-mortar stores. Additionally, online sellers can often keep more of the profits from their sales since there is no need for overhead costs like rent or staff salaries. Finally, buyers can purchase products from anywhere in the world, making it an ideal way to sell products to customers who may not be able to visit your store.\\"},{\\"id\\":3,\\"title\\":\\"The different types of marketing techniques that can be used to sell products online\\",\\"paragraph\\":\\"There are many different marketing techniques that can be used to sell products online. Some of the most common methods include email marketing, social media marketing, and online advertising. Each of these methods has its own strengths and weaknesses, so it's important to choose the right one for your product and target audience.\\n\\nEmail Marketing\\nEmail marketing is probably the most common type of marketing online. It's simple to set up and use, and it can be very effective at reaching a wide audience. Email campaigns can be targeted based on location, age, or interests, which makes them versatile tools for businesses of all sizes.\\n\\nOne downside of email marketing is that it can be difficult to track results. This is because email addresses are often anonymous (or at least not easily traceable). If you're looking for detailed feedback on your campaign performance, email marketing may not be the best option.\\n\\nSocial Media Marketing\\nSocial media platforms like Facebook and Twitter are great ways to connect with potential customers directly. They're also great channels for promoting your products and services. Social media platforms are especially useful for small businesses that don't have a lot of money to spend on advertising campaigns.\\n\\nOne downside of social media marketing is that it can be time-consuming (and sometimes expensive) to maintain a strong presence on these platforms.\\"},{\\"id\\":4,\\"title\\":\\"Tips for setting up an effective online store\\",\\"paragraph\\":\\"Setting up an online store can be a daunting task, but with a little preparation and some helpful tips, it can be a successful venture. Here are five tips for setting up an effective online store:\\n\\n1. Choose the right platform. There are many different platforms available to set up an online store, and it is important to choose the one that will best suit your needs. Some popular options include Shopify, WordPress, and Drupal. Each has its own strengths and weaknesses, so it is important to decide which one will work best for your business before starting construction.\\n\\n2. Plan your layout carefully. Once you have chosen a platform, the next step is to plan your layout. Make sure all of your content is easily accessible from the home page and that all of your products are organized in logical categories. You also want to make sure that you have enough space to display pictures and product information.\\n\\n3. Build a strong branding strategy. One of the most important aspects of setting up an online store is creating a strong branding strategy. Make sure all of your content (including product descriptions, images, and pricing) reflects the image you want to project for your business. Also consider developing marketing materials (such as flyers or web ads) that target specific demographics or interests related to your products.\\n\\n4. Get organized early on In order to run an effective online store, you need to get organized from the start. Set up standard shipping procedures and create labels for each product so that customers know exactly what they're paying for when they checkout\u3002 Also make sure you have automated systems in place (such as order tracking software) so you can keep track of inventory levels and customer activity\u3002 Finally, keep accurate records of all sales data so you can measure progress over time and make necessary adjustments\u3002\\n\\n5 . Stay focused on customer needs In order to keep customers coming back again and again, it is essential that you focus on their needs first and foremost\u3002 Make sure all of your content (including product descriptions, images, pricing information, etc.\\"},{\\"id\\":5,\\"title\\":\\"How to create a successful ecommerce website\\",\\"paragraph\\":\\"Creating a successful ecommerce website is not as difficult as one might think. There are a few key things that need to be in place for any website to be successful, and these include: an effective search engine optimization strategy, effective marketing techniques, and an attractive design.\\n\\nOne of the most important aspects of any ecommerce website is its search engine optimization (SEO). A well-optimized website will rank higher on search engines results pages (SERPs), which will lead to increased traffic and sales. There are a number of different SEO techniques that can be used to achieve this, including keyword research, on-page optimization, and link building.\\n\\nEffective marketing also plays a major role in the success of any ecommerce website. It is essential that the site has a clear mission statement and target market, as well as clear product descriptions and images. Additionally, regular blog posts should be written about new products or upcoming sales events, in order to keep customers informed about what\u2019s happening with the business.\\n\\nFinally, it\u2019s important to have an attractive design if the goal is to attract more visitors and customers. A well-designed site will look professional and sleek \u2013 making it easier for potential buyers to find information they\u2019re looking for and making the purchase process more enjoyable overall.\\"},{\\"id\\":6,\\"title\\":\\"The importance of social media when selling products online\\",\\"paragraph\\":\\"When selling products online, social media is an important tool. Social media allows customers and potential customers to connect with the business in a way that was never possible before. It also allows businesses to interact with their customers in a more personal way than ever before. This interaction can help build trust and credibility between the business and its customer base. Additionally, social media can be used to promote the product directly to potential customers. This can help increase sales by reaching new buyers who may not have otherwise known about the product. Overall, social media is an essential part of any online sales strategy.\\"},{\\"id\\":7,\\"title\\":\\"The top mistakes made by ecommerce entrepreneurs\\",\\"paragraph\\":\\"1. Not setting realistic expectations for their business. Many entrepreneurs assume that starting an online store is as easy as filling out a few forms and uploading some pictures, when in reality it takes a lot of hard work and dedication to succeed. Before starting your own ecommerce business, make sure you understand what it will take to achieve success and set reasonable goals for yourself.\\n\\n2. Focusing too much on the wrong metrics. It\u2019s important to be aware of your business\u2019s key performance indicators (KPIs), but don\u2019t let them drive your decisions more than anything else. Instead, focus on making your store as successful as possible based on customer satisfaction and retention rates rather than raw numbers alone.\\n\\n3. Making poor choices with their marketing strategy. Once your store is up and running, make sure you invest in effective marketing campaigns that will bring in new customers. However, don\u2019t forget to keep track of your spending so you can stay within budget \u2013 overspending on marketing can lead to disastrous results down the line!\\n\\n4. Ignoring the importance of customer service . No matter how good your product or service may be, if customers have trouble using it or finding what they need, they\u2019re likely going to leave negative reviews online or even stop shopping at all. Make sure you have a solid customer service plan in place that can handle any issues that arise \u2013 no matter how small they may seem at first glance!\\"}]\"",
    "saved": 1,
    "created_at": "05-09-2022",
    "updated_at": "05-09-2022",
    "title": "What is the best way to sell products online and explain the different types of marketing techniques.",
    "language": "English US"
}

My goal is to load the article key to this variable in vue:

this.blogTitles = JSON.parse(response.data.r.article);

But, instead of having an object, it is returning a typeof "string"

as(the below output is detected as a string)

[{"id":1,"title":"Types of products that can be sold online","paragraph":"When it comes to shopping, many people prefer to do so online. There are a variety of reasons for this: convenience, price comparison, and selection. Here are some types of products that can be sold online: \n\n1. Clothing and accessories: Whether you're looking for something new to wear or just need a few new pieces of jewelry, you can find them all online. Plus, there's no need to leave the comfort of your home! \n\n2. Home goods: From towels and sheets to furniture and appliances, you can find everything you need to furnish your home without ever leaving the comfort of your own couch or bed. Plus, with prices often being lower than in stores, why not shop around before making a purchase? \n\n3. Food: If you're looking for something special in the way of cuisine (or just want to save money), look no further than the internet! You can find everything from international recipes to quick and easy meal ideas. And don't forget about those hard-to-find ingredients - they're often much cheaper online than in stores!"},{"id":2,"title":"Benefits of selling products online","paragraph":"There are many benefits to selling products online, including the ability to reach a wider audience than you would if selling through brick-and-mortar stores. Additionally, online sellers can often keep more of the profits from their sales since there is no need for overhead costs like rent or staff salaries. Finally, buyers can purchase products from anywhere in the world, making it an ideal way to sell products to customers who may not be able to visit your store."},{"id":3,"title":"The different types of marketing techniques that can be used to sell products online","paragraph":"There are many different marketing techniques that can be used to sell products online. Some of the most common methods include email marketing, social media marketing, and online advertising. Each of these methods has its own strengths and weaknesses, so it's important to choose the right one for your product and target audience.\n\nEmail Marketing\nEmail marketing is probably the most common type of marketing online. It's simple to set up and use, and it can be very effective at reaching a wide audience. Email campaigns can be targeted based on location, age, or interests, which makes them versatile tools for businesses of all sizes.\n\nOne downside of email marketing is that it can be difficult to track results. This is because email addresses are often anonymous (or at least not easily traceable). If you're looking for detailed feedback on your campaign performance, email marketing may not be the best option.\n\nSocial Media Marketing\nSocial media platforms like Facebook and Twitter are great ways to connect with potential customers directly. They're also great channels for promoting your products and services. Social media platforms are especially useful for small businesses that don't have a lot of money to spend on advertising campaigns.\n\nOne downside of social media marketing is that it can be time-consuming (and sometimes expensive) to maintain a strong presence on these platforms."},{"id":4,"title":"Tips for setting up an effective online store","paragraph":"Setting up an online store can be a daunting task, but with a little preparation and some helpful tips, it can be a successful venture. Here are five tips for setting up an effective online store:\n\n1. Choose the right platform. There are many different platforms available to set up an online store, and it is important to choose the one that will best suit your needs. Some popular options include Shopify, WordPress, and Drupal. Each has its own strengths and weaknesses, so it is important to decide which one will work best for your business before starting construction.\n\n2. Plan your layout carefully. Once you have chosen a platform, the next step is to plan your layout. Make sure all of your content is easily accessible from the home page and that all of your products are organized in logical categories. You also want to make sure that you have enough space to display pictures and product information.\n\n3. Build a strong branding strategy. One of the most important aspects of setting up an online store is creating a strong branding strategy. Make sure all of your content (including product descriptions, images, and pricing) reflects the image you want to project for your business. Also consider developing marketing materials (such as flyers or web ads) that target specific demographics or interests related to your products.\n\n4. Get organized early on In order to run an effective online store, you need to get organized from the start. Set up standard shipping procedures and create labels for each product so that customers know exactly what they're paying for when they checkout。 Also make sure you have automated systems in place (such as order tracking software) so you can keep track of inventory levels and customer activity。 Finally, keep accurate records of all sales data so you can measure progress over time and make necessary adjustments。\n\n5 . Stay focused on customer needs In order to keep customers coming back again and again, it is essential that you focus on their needs first and foremost。 Make sure all of your content (including product descriptions, images, pricing information, etc."},{"id":5,"title":"How to create a successful ecommerce website","paragraph":"Creating a successful ecommerce website is not as difficult as one might think. There are a few key things that need to be in place for any website to be successful, and these include: an effective search engine optimization strategy, effective marketing techniques, and an attractive design.\n\nOne of the most important aspects of any ecommerce website is its search engine optimization (SEO). A well-optimized website will rank higher on search engines results pages (SERPs), which will lead to increased traffic and sales. There are a number of different SEO techniques that can be used to achieve this, including keyword research, on-page optimization, and link building.\n\nEffective marketing also plays a major role in the success of any ecommerce website. It is essential that the site has a clear mission statement and target market, as well as clear product descriptions and images. Additionally, regular blog posts should be written about new products or upcoming sales events, in order to keep customers informed about what’s happening with the business.\n\nFinally, it’s important to have an attractive design if the goal is to attract more visitors and customers. A well-designed site will look professional and sleek – making it easier for potential buyers to find information they’re looking for and making the purchase process more enjoyable overall."},{"id":6,"title":"The importance of social media when selling products online","paragraph":"When selling products online, social media is an important tool. Social media allows customers and potential customers to connect with the business in a way that was never possible before. It also allows businesses to interact with their customers in a more personal way than ever before. This interaction can help build trust and credibility between the business and its customer base. Additionally, social media can be used to promote the product directly to potential customers. This can help increase sales by reaching new buyers who may not have otherwise known about the product. Overall, social media is an essential part of any online sales strategy."},{"id":7,"title":"The top mistakes made by ecommerce entrepreneurs","paragraph":"1. Not setting realistic expectations for their business. Many entrepreneurs assume that starting an online store is as easy as filling out a few forms and uploading some pictures, when in reality it takes a lot of hard work and dedication to succeed. Before starting your own ecommerce business, make sure you understand what it will take to achieve success and set reasonable goals for yourself.\n\n2. Focusing too much on the wrong metrics. It’s important to be aware of your business’s key performance indicators (KPIs), but don’t let them drive your decisions more than anything else. Instead, focus on making your store as successful as possible based on customer satisfaction and retention rates rather than raw numbers alone.\n\n3. Making poor choices with their marketing strategy. Once your store is up and running, make sure you invest in effective marketing campaigns that will bring in new customers. However, don’t forget to keep track of your spending so you can stay within budget – overspending on marketing can lead to disastrous results down the line!\n\n4. Ignoring the importance of customer service . No matter how good your product or service may be, if customers have trouble using it or finding what they need, they’re likely going to leave negative reviews online or even stop shopping at all. Make sure you have a solid customer service plan in place that can handle any issues that arise – no matter how small they may seem at first glance!"}]

I am very surprised as this looks more like an object.....

Any idea what is happening please? I have been for hours on this to no end.

Thanks!

0 likes
7 replies
tykus's avatar

What does the Model class look like - what cast/accessor do you have for that column?

LaraBABA's avatar

@tykus Sorry for the late reply, this is the model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    use HasFactory;

    protected $table = 'articles';

    protected $fillable = [
        'user_id',
        'title',
        'language',
        'article',
        'saved',
        'created_at',
        'updated_at',
    ];

    protected $casts = [
        'created_at' => 'datetime:d-m-Y',
        'updated_at' => 'datetime:d-m-Y',
    ];

    public function user()
    {
        return $this->belongsTo(\App\Models\User::class, 'id', 'user_id');
    }
}
tykus's avatar
tykus
Best Answer
Level 104

@User476820 add a cast for the article property

protected $casts = [
    'article' => 'array',
    'created_at' => 'datetime:d-m-Y',
    'updated_at' => 'datetime:d-m-Y',
];
1 like
LaraBABA's avatar

@tykus How on earth did you work out this one lol :-) Could you please explain?

Your solution works but I am still not understanding why would it not be an array without the casting.

tykus's avatar

@User476820 because the "JSON" data in the database is just text; there is nothing to tell PHP that it should be JSON unless you make that cast. The cast causes the string to be json_decoded, and then it becomes useable

Please or to participate in this conversation.