DEV Community

loading...

Laravel Form Validation

kingsconsult profile image Kingsconsult Updated on ・3 min read

Hello, Happy New Year, Hope you are enjoying the yuletide period? Today, I am going to write on Form Validation in Laravel. When we are building an application that requires a user filling a form and the application storing the data in the database, there is always a need to validate, if not, a user can decide or mistakenly enter the wrong data in a field and summit and the application will process it, but if there are some validation rules before the storing method will process it, it will return an error to check the form input.
Laravel has some default validation rules out of the box, but there are some instances we will want to define our own set of rules. There might be a complex scenario so you will need to create a form request, also in programming, the SRP of SOLID principle states that a class should perform just one task, so our store method of controller needs to only handle storing of data and not validation.
Let's dive in, you will understand it better.

Click on my profile to follow me to get more updates.

Step 1: Create Form Request

To create a form request, we are going to use an artisan command

php artisan make:request StoreProjectRequest

A folder called Requests will be created in app/Http/ directory with the StoreProjectRequest.php file, open the file and let's write our validation rules.
storeProjectRequest

Step 2: Write the Validation rules

Go to app/Http/Requests/StoreProjectRequest.php
All the fields that we want to validate should be written in a key-value pair in the return of the rules methods

    public function rules()
    {
        return [
            'name' => 'required|max:100',
            'introduction' => 'required|max:255',
            'location' => 'nullable',
            'cost' => 'required|integer'
        ];
    }
Enter fullscreen mode Exit fullscreen mode

Step 3: Write the error messages

This is optional because Laravel has provided a set of error messages. However, we can decide to write our error messages for each error.
Create a method called message() and return an array of the error messages.

    public function messages()
    {
        return [
            'name.required' => 'You need to provide the name of the project',
            'name.max' => 'The name of the project should not be greater than 100 characters',
            'introduction.required' => 'Please provide the introduction of the project',
            'cost.integer' => 'The cost of the project must be a number'
        ];
    }
Enter fullscreen mode Exit fullscreen mode

So, the StoreProjectRequest will now look like this
StoreProjectRequest

Step 4: Type-hint the Request in the Controller

Now go to our controller, and the store method where we want to validate, then type-hint the StoreProjectRequest replacing the usual Request

   public function store(StoreProjectRequest $request)
    {
        $request->validated();

        Project::create($request->all());

        return redirect()->route('projects.index')
            ->with('success', 'Project created successfully.');
    }
Enter fullscreen mode Exit fullscreen mode

You can retrieved the validated request like this

$validated = $request->validated();

So you can use it like this

$projectName = $validated["name"];

If there is an error, the errors will be stored in the error bag and send back to the view or store in the session.

Testing

Run your app and go to create a page
create project
Try to submit a form with values which violates the rules of our validation and try to submit
create page with errors

Follow me for more of my articles, you can leave comments, suggestions, and reactions.
I am open to any vacancy as a PHP (Laravel) backend engineer, I am also available for any job.

click the link to view my profile and follow me

Thank you for your time

Discussion (0)

Forem Open with the Forem app