Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

Validation, Errors and Status Codes

Premium
5:34

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 of our courses? (31 h 16 min)

You also get:

55 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

A
Ariziky ✓ Link copied!

Hi, how to can i customize error message format in laravel 11 ?

N
Nerijus ✓ Link copied!

If you are using form requests then the same way. Nothing changed with laravel 11

A
Ariziky ✓ Link copied!

Laravel Validation returns an error as a JSON response with the error messages in a strict standard format. What if you want to change it to an entirely different structure because your front-enders ask you for specific key-value pairs? I found this article wicth is based on laravel 10 https://laraveldaily.com/post/laravel-validation-completely-customize-error-message-format. But with laravel 11, there is bootstrap folder which manages exceptions, middleware and others ...

N
Nerijus ✓ Link copied!

You do the same in the bootstrap/app.