-1

Returning laravel resource is giving null but the database have files. here is my resource class

class UsersResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
    'u_id' => $this->user_id,
    'u_name' => $this->user_name,
    ];
    }
}

My route file is here

Route::get('test2', function(){
    $xyx=Users::find(1);
    return new UsersResource($xyx);
});

My response is here as follows

{"data":{"u_id":null,"u_name":null}}

thanks

Khal
  • 219
  • 5
  • 19

2 Answers2

1

It's because Users table doesn't contain user_id or user_name columns by default. It's id and name by default. So you should change the code like below.

class UsersResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */

    public function toArray($request)
    {
        return [
           'u_id' => $this->id,
           'u_name' => $this->name,
        ];
    }
}
Alex
  • 1,148
  • 8
  • 30
0

Laravel Resource does just formatting your Eloquent Model. Check out the querying result(in your case, $xyx) first.

dd($xyx);

As mentioned by @Alexandr-Biship, you may try to access wrong field.

Meow Kim
  • 445
  • 4
  • 14