Код: Выделить всё
//for index
$books = Book::factory(2)->create();
//for show
$books = Book::factory()->create();
< /code>
simplax () синтаксис на getjson на обеих функциях привела к «попытке прочитать свойство« имя »на NULL» при неудаче, но в противном случае получили данные, когда тест преуспевает.public function definition(): array
{
return [
'book_code' => fake()->unique()->text(10),
'book_title' => fake()->text(20),
'author' => fake()->name(),
'category' => rand(0, 5),
'publisher' => fake()->text(20),
'stock' => rand(1, 10),
'book_desc' => fake()->text(120),
];
}
< /code>
Это для контроллера книги API < /p>
public function index(): JsonResponse
{
$book = Book::all();
return $this->sendResponse(BookResource::collection($book), 'Books retrieved successfully.');
}
public function show($id): JsonResponse
{
$book = Book::find($id);
if (is_null($book)) {
return $this->sendError('Book not found.');
}
if ($book->stock sendResponse(new BookResource($book), "Book can't be rented");
}
return $this->sendResponse(new BookResource($book), 'book retrieved successfully.');
}
< /code>
Это для книжного ресурса < /p>
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'book_code' => $this->book_code,
'book_title' => $this->book_title,
'author' => $this->author,
'category' => $this->categories->name,
'publisher' => $this->publisher,
'stock' => $this->stock,
'book_cover' => $this->book_cover,
'book_desc' => $this->book_desc,
'barcode' => $this->book_desc,
];
}
Подробнее здесь: https://stackoverflow.com/questions/796 ... in-laravel