Naimur Rahaman
Naimur Rahaman

Reputation: 3

Need help on laravel resource

I am newbie on Laravel. I was trying to make an API using Laravel Resource. The Following Code Works well,

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\Resource;

class Word extends Resource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return parent::toArray($request);
    }
}

But When I try with the following, this doesn't work,

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\Resource;

class Word extends Resource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'word' => $this->word_name
        ];
    }
}

The error shown is,

Undefined index: word_name

But I have word_name column in my table. I would be grateful if anybody help me.

I am using showapi() method to load the resource.

public function showapi()
{
    WordResource::withoutWrapping();
    return new WordResource(Word::all());
}

Upvotes: 0

Views: 695

Answers (2)

bilal
bilal

Reputation: 3

you have to define variable word_name as member of Word class.

Upvotes: 0

linktoahref
linktoahref

Reputation: 7972

Since you are passing a collection to the Resource, you can't directly access the properties of the Modal. Instead for the resource instance you would get a Collection, giving you access to the collection methods. So you could change your resource toArray() as

public function toArray($request)
{
    return $this->pluck('word_name')->keyBy(function ($item) {

        return 'word';

    });
}

Upvotes: 1

Related Questions