У меня есть ответ json. В разделе данные мне нужно получить только uID и Эл. адрес. Я пробую использовать JsonResource, но выдает ошибку.
Это ответ json без JsonResource
{
"current_page": 1,
"data": [
{
"uID": 1,
"name": "supun",
"email": "[email protected]",
"email_verified_at": null,
"dob": null,
"contactNo": null,
"fbID": null,
"googleID": null,
"bloodGroup": null,
"height": null,
"weight": null,
"lID": 1,
"sID": 1,
"created_at": "2018-10-24 02:41:47",
"updated_at": "2018-10-24 02:41:47",
"deleted_at": null
},
{
"uID": 4,
"name": "supun",
"email": "[email protected]",
"email_verified_at": null,
"dob": null,
"contactNo": null,
"fbID": null,
"googleID": null,
"bloodGroup": null,
"height": null,
"weight": null,
"lID": 1,
"sID": 1,
"created_at": "2018-10-24 02:52:17",
"updated_at": "2018-10-24 02:52:17",
"deleted_at": null
}
],
"first_page_url": "http://127.0.0.1:8000/api/users?page=1",
"from": 1,
"last_page": 3,
"last_page_url": "http://127.0.0.1:8000/api/users?page=3",
"next_page_url": "http://127.0.0.1:8000/api/users?page=2",
"path": "http://127.0.0.1:8000/api/users",
"per_page": 2,
"prev_page_url": null,
"to": 2,
"total": 5
}
Это ответ, который мне нужно создать с помощью jsonresource
{
"current_page": 1,
"data": [
{
"uID": 1,
"email": "[email protected]"
},
{
"uID": 4,
"email": "[email protected]"
}
],
"first_page_url": "http://127.0.0.1:8000/api/users?page=1",
"from": 1,
"last_page": 3,
"last_page_url": "http://127.0.0.1:8000/api/users?page=3",
"next_page_url": "http://127.0.0.1:8000/api/users?page=2",
"path": "http://127.0.0.1:8000/api/users",
"per_page": 2,
"prev_page_url": null,
"to": 2,
"total": 5
}
Это мой пользователь UserController
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Support\Facades\Auth;
use App\Http\Resources\Users as GetAllUsersResource;
use Validator;
class UserController extends Controller {
public function usersApi( Request $request ) {
$userInfo = User::paginate(2);
$output = new GetAllUsersResource($userInfo);
return response()->json($output, $this->successStatus);
// return response()->json(['status' => true,
// 'message' => 'done',
// 'data' => $output
// ], $this->successStatus);
}
}
а это мой JsonResource
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class Users extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
//return parent::toArray($request->data);
return [
'uID' =>$this->uID,
'email' =>$this->email,
];
}
}
Это ошибка, которую я получил после добавления ее в JsonResource
"message": "Undefined property: Illuminate\\Pagination\\LengthAwarePaginator::$uID",
"exception": "ErrorException",
"file": "E:\\xampp\\htdocs\\myworks\\pharmeasylk\\vendor\\laravel\\framework\\src\\Illuminate\\Http\\Resources\\DelegatesToResource.php",
"line": 120,
Я пробовал много других способов, но безуспешно. это работает только в том случае, если пользователь возвращает только одну строку. но разбивка на страницы содержит много пользовательских данных и данных ссылок. Если кто-то может мне с этим помочь. большая помощь.

что делает метод __construct() в классе GetAllUsersResource
$output = new GetAllUsersResource($userInfo);
вы могли бы захотеть сделать это вместо этого !?
$output = new GetAllUsersResource($userInfo->items());
извините, обращайтесь к нему как к методу items(). он вернет массив с пользователями в нем
Но, сэр, мне нужны и другие данные, такие как (last_page, per_page , total), после добавления $output = new GetAllUsersResource($userInfo->items()); он дает мне эту ошибку Trying to get property 'uID' of non-object
разместите в своем вопросе класс GetAllUserResource
Похоже, вы передаете коллекцию классу Illuminate\Http\Resources\Json\JsonResource (который ожидает получить один объект) вместо того, чтобы передавать ее классу Illuminate\Http\Resources\Json\ResourceCollection, который ожидает получить коллекцию.
Из документов:
In addition to generating resources that transform individual models, you may generate resources that are responsible for transforming collections of models. This allows your response to include links and other meta information that is relevant to an entire collection of a given resource.
To create a resource collection, you should use the --collection flag when creating the resource. Or, including the word Collection in the resource name will indicate to Laravel that it should create a collection resource. Collection resources extend the Illuminate\Http\Resources\Json\ResourceCollection class:
php artisan make:resource Users --collection
php artisan make:resource UserCollection
https://laravel.com/docs/5.7/eloquent-resources#generating-resources
Если вы не делаете ничего необычного для преобразования своей коллекции, это также может сработать без изменения вашего класса JsonResource:
$output = GetAllUsersResource::collection($userInfo);
Хорошо, сэр, я сделал, как вы упомянули, но я получаю эту ошибку
Cannot access protected property Illuminate\\Pagination\\LengthAwarePaginator::$items. Я новичок в Laravel. Можете ли вы мне немного объяснить.