Skip to content

Instantly share code, notes, and snippets.

@elmarputz
Created March 15, 2019 08:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elmarputz/195215d506e0248b666771a16be32534 to your computer and use it in GitHub Desktop.
Save elmarputz/195215d506e0248b666771a16be32534 to your computer and use it in GitHub Desktop.
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