In this lesson, we will finalize our resource Controller with two missing methods: update and delete the category.
First, the update method. The method for the Route is PUT, and in the Controller, the method is usually update.
routes/api.php:
Route::get('/user', function (Request $request) { return $request->user();})->middleware('auth:sanctum'); Route::get('categories', [\App\Http\Controllers\Api\CategoryController::class, 'index']);Route::get('categories/{category}', [\App\Http\Controllers\Api\CategoryController::class, 'show']);Route::post('categories', [\App\Http\Controllers\Api\CategoryController::class, 'store']);Route::put('categories/{category}', [\App\Http\Controllers\Api\CategoryController::class, 'update']); Route::get('products', [\App\Http\Controllers\Api\ProductController::class, 'index']);
app/Http/Controllers/Api/CategoryController.php:
class CategoryController extends Controller{ // ... public function update(Category $category, StoreCategoryRequest $request) { $category->update($request->all()); return new CategoryResource($category); }}
In the Controller, we use a Route Model Binding to find a record and the same Form Request for validation. In the update method, we update the category and return the updated category.
In the client, we can send...
Thank you.
when updating and creating data, I would not write : request->all(), but would write the validated data: request->safe()
or
request->validated()Delete does not work on categories that has products linked to it and throws "Integrity constraint violation: 19 FOREIGN KEY constraint failed" the migration needs to have onDelete
$table->foreignId('category_id')->constrained()->onDelete('cascade');
In theory you wouldn't want to delete products as they would be sold. Also, there's a helper
cascadeOnDelete()On cascade delete we can do something like this, please let me know is there any easiest way
As far as I'm aware - this is the most common way to deal with this issue. So I don't think that there's a better way
Would moving this category product check to a DeleteCategoryFormRequest be consistent with StoreCategoryRequest?