First of all I have Book
DB field and BookReview
DB field
Book Model:
public function reviews()
{
return $this->hasMany(BookReview::class);
}
BookReview Model:
public function book()
{
return $this->belongsTo(Book::class);
}
What I need to do is to delete a BooksReview
, but it consists in a relationship with Book
field
This is the route
Route::delete('/books/{bookId}/reviews/{reviewId}');
And this is the controller:
public function destroy(int $bookId, int $reviewId, Request $request)
{
// TODO: implement
$check_bookReview = BookReview::firstWhere('id', $reviewId);
if ($check_bookReview) {
BookReview::destroy($id);
return response()->noContent();
} else {
abort(404);
}
}
I've never tried to delete data with a relation before, how do I accomplish this?
Thank you in advance
CodePudding user response:
You can leverage Route Model Binding to have Laravel automatically attempt to find and return the relevant models from your database based on the URI parameters defined in your route and associated function:
Route::delete('/books/{bookId}/reviews/{reviewId}', [BookReviewController::class, 'destroy');
public function destroy(Request $requst, Book $bookId, BookReview $reviewId)
{
$bookId->delete();
return response()->json([], 204);
}
Laravel will automatically attempt to find and return the relevant Book
and BookReview
models from the database based on the value of each parameter. If it can't find the relevant model it will fail with a 404
but otherwise, the value of each parameter will be that of a model. Note that the name of the parameters defined in the Route
and function definitions must match for route model binding to work.
CodePudding user response:
Instead of:❌
public function destroy(int $bookId, int $reviewId, Request $request)
{
// @TODO implement
$check_bookReview = BookReview::firstWhere('id', $reviewId);
if ($check_bookReview) {
BookReview::destroy($id);
return response()->noContent();
}
else {
abort(404);
}
}
Use this: ✅
public function destroy(int $bookId, int $reviewId, Request $request)
{
if (BookReview::destroy($reviewId)) {
return response()->noContent();
} else {
abort(404);
}
}
\Illuminate\Database\Eloquent\Model::destroy($ids) returns a total count of destroyed models for the given IDs.