简体   繁体   中英

Laravel REST API route Problem in Resource file

<?php

namespace App\Http\Resources\Product;

use Illuminate\Http\Resources\Json\JsonResource;

class ProductResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
        

            'href' => [
                'self' => route('reviews.index', $this->id),
            ]
        ];
    }
}

My Route Is Coming "href":{"self":"http:\/\/127.0.0.1:8000\/api\/products\/1\/reviews"} like this, How am I gonna solve it? thank you

It's happening because of json response. json alway encode the code, so You can use JSON_UNESCAPED_SLASHES to skip url slashes

response()->json(..., 200, [], JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT);

In laravel eloquent api resource also have the same problem.The best way to apply json options to your Response or ResponseCollection is:

public function withResponse($request, $response)
{
    $response->setEncodingOptions(JSON_UNESCAPED_SLASHES);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM