Courses

How to Build Laravel 12 API From Scratch

Validation, Errors and Status Codes

You're reading a FREE PREVIEW of a PREMIUM course.
Summary of this lesson:
- Form Request validation for API endpoints
- Proper error handling and status codes
- Frontend error handling with axios

Video Version of the Lesson

[Only for premium members]

Link to the repository

[Only for premium members]

Now, let's talk about validation. What happens if the user doesn't pass anything?

First, let's see what we get if we don't send the name field.

We get a 500 error code and a SQL error message, which is also a security issue. We don't want customers to see the actual error.


For the backend part, we can validate the regular way using Form Request.

php artisan make:request StoreCategoryRequest

app/Http/Requests/StoreCategoryRequest.php:

class StoreCategoryRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
 
public function rules(): array
{
return [
'name' => ['required']
];
}
}

app/Http/Controllers/Api/CategoryController.php:

use App\Http\Requests\StoreCategoryRequest;
 
class CategoryController extends Controller
{
// ...
 
public function store(Request $request)
public function store(StoreCategoryRequest $request)
{
$category = Category::create($request->all());
 
return new CategoryResource($category);
}
}

Now, we see a better result that can be shown...

The full lesson is only for Premium Members.
Want to access all 28 video+text lessons of this course? (1 h 21 min)

You also get:

  • 83 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord