Created
March 15, 2019 08:36
-
-
Save elmarputz/195215d506e0248b666771a16be32534 to your computer and use it in GitHub Desktop.
Book Update
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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