Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Book Update
public function update(Request $request, string $isbn) : JsonResponse
{
DB::beginTransaction();
try {
$book = Book::with(['authors', 'images', 'user'])
->where('isbn', $isbn)->first();
if ($book != null) {
$request = $this->parseRequest($request);
$book->update($request->all());
//delete all old images
$book->images()->delete();
// save images
if (isset($request['images']) && is_array($request['images'])) {
foreach ($request['images'] as $img) {
$image = Image::firstOrNew(['url'=>$img['url'],'title'=>$img['title']]);
$book->images()->save($image);
}
}
//update authors
$ids = [];
if (isset($request['authors']) && is_array($request['authors'])) {
foreach ($request['authors'] as $auth) {
array_push($ids,$auth['id']);
}
}
$book->authors()->sync($ids);
$book->save();
}
DB::commit();
$book1 = Book::with(['authors', 'images', 'user'])
->where('isbn', $isbn)->first();
// return a vaild http response
return response()->json($book1, 201);
}
catch (\Exception $e) {
// rollback all queries
DB::rollBack();
return response()->json("updating book failed: " . $e->getMessage(), 420);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.