0

Im new to Laravel Rest APIs. While trying tutorials I got this error of showing the link to the next route.

{  
    "data":{  
        "name":"mollitia",
        "totalPrice":307.44,
        "rating":5,
        "href":{  
            "reviews":"http:\/\/127.0.0.1:8000\/api\/product\/5\/reviews"
        }
    }
}

I need to get the href for reviews as,

"reviews":"http://127.0.0.1:8000/api/products/5/reviews"

resource:

<?php
namespace App\Http\Resources\Product;
use Illuminate\Http\Resources\Json\Resource;
class ProductResource extends Resource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'name' => $this->name,
            'totalPrice' => round(( 1 - ($this->discount/100)) * $this->price,2),
            'rating' => $this->reviews->count() > 0 ? round($this->reviews->sum('star')/$this->reviews->count(),2) : 'No rating yet',
            'href' => [
                'reviews' => route('reviews.index',$this->id)
            ]
        ];
    }
}

What have I done wrong?

shavindip
  • 607
  • 9
  • 27
  • How should the URL look? – Jonathon Oct 31 '18 at 08:30
  • @Jonathon it should look like http ://127.0.0.1:8000/api/products/5/reviews – shavindip Oct 31 '18 at 08:33
  • 1
    That's what it looks like you're getting. The only difference I see is the backslashes (\\), before the forward slashes (/), which is expected as it is correct for the JSON format. When whatever it is consumes your API receives your response, it will be decoded into the URL without those backslashes – Jonathon Oct 31 '18 at 08:38
  • Thanks a lot for your response. I was confused by the backslash and thought its an error. – shavindip Oct 31 '18 at 08:43
  • 1
    No worries. There's probably a way you can make it so that the forward slashes are not escaped with backslashes, but I think the purpose of it is to make the JSON itself more portable in that it can be embedded into HTML/script tags etc. [without causing problems](https://stackoverflow.com/questions/1580647/json-why-are-forward-slashes-escaped). – Jonathon Oct 31 '18 at 08:44
  • Ans is already there https://stackoverflow.com/questions/50998771/laravel-json-response-without-backslashes – Jasim Juwel Dec 05 '20 at 08:45

0 Answers0