Courses

How to Build Laravel 11 API From Scratch

Finishing CRUD: Update, Delete and Resource Controller

Summary of this lesson:
- Implementing PUT and DELETE endpoints
- Handling response codes
- Using apiResource for route grouping

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...

The full lesson is only for Premium Members.
Want to access all 23 lessons of this course? (58 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord