LARAVEL 5.7 JSONResource toArray ERROR: Declaration should be compatible

62 Views Asked by At

I have an problem using JSON Resource to Array converter in Laravel. My code like this:

DataResource.php

<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class DataResource extends JsonResource
{
  public function toArray(Request $request)
  {
    return parent::toArray($request);
  }
}

UserController.php

<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Resources\DataResource;

class UserController extends Controller
{
  public function showUser()
  {
    $Users = User::get();
    return new DataResource($Users);
  }
}

I used that code in my localhost using Laravel 10 and it run fine without any problem. But when I upload that code in my webhosting using Laravel 5.7. It give me an error:

Declaration of App\Http\Resources\DataResource::toArray(Illuminate\Http\Request $request) should be compatible with Illuminate\Http\Resources\Json\JsonResource::toArray($request)

I don't know what the problem, the code is same, but different version of Laravel show that error. My Website still using Laravel 5.7 and not upgrade because there is too many change and work if I upgrade it.

Please give me some advice, thanks in advance

1

There are 1 best solutions below

0
Akash prajapati On

The toArray method signature should not include the Request type hint. Instead, it should simply accept no parameters or accept any necessary parameters for customizing the resource transformation. Here's the corrected version of your DataResource class:

<?PHP

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

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

In Laravel 5.7 the declaration of Illuminate/Http/Resources/Json /JsonResource.php@toArray is as follow

/**
 * Transform the resource into an array.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
public function toArray($request)
{
    if (is_null($this->resource)) {
        return [];
    }
    return is_array($this->resource)
        ? $this->resource
        : $this->resource->toArray();
}

Please let me know in case of still any issue.