Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

RomainB's avatar
Level 13

API Resource: id of relation isn't returned when freshly created

[EDIT] Found the solution by retrieving the Keyword model from the database

$keyword = $website->keywords()->create([
    'text' => $request->input('text')
]);

return new KeywordResource($website->keywords()->find($keyword->id)); // From database

Hi all, I'm working on an API with some relationships, for example, a "Website" model and a "Keyword" one

In AliasController@store, I create the model with "relationship call":

    public function store(Request $request)
    {
        $user = $request->user();
        $website = $user->websites()->findOrFail($request->input('website_id'));

        $keyword = $website->keywords()->create([
            'text' => $request->input('text')
        ]);

        return new KeywordResource($keyword);
    }

and here is my resource:

    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'text' => $this->text,
            'website_id' => $this->pivot->website_id
        ];
    }

My problem is website_id is not provided on the JSON response, why? and how to do so?

In AliasController@index, it works correctly:

    public function index(Request $request)
    {
        $user = $request->user();
        $website = $user->websites()->findOrFail($request->input('website_id'));
        
        return KeywordResource::collection($website->keywords);
    }
0 likes
1 reply
tykus's avatar

Whenever you create the Keyword using the relationship, you do not get the Pivot whereas you do whenever you fetch the keywords through the $website. If you want the website_id in the Resource, you will need to load the relationship on the newly created $keyword:

Please or to participate in this conversation.