Laravel Server Side Validation Example Using Resource Controller

This Laravel tutorial help to understand server-side validation using laravel 8/9. The PHP Laravel is the fastest growing PHP MVC Framework. We will apply the validation rule to upcoming requests using the validation class. I am extending my previous laravel tutorial Laravel 5.6 CRUD Tutorial Using Resource Controller.

This Laravel 5 tutorial help to add server-side validation into the HTML form view template. We will create add new employee record functionality and validate data against non-empty input data.

Laravel provides several different approaches to validate form data into your applications. By default, Laravel’s uses ValidatesRequests, Which provides a convenient method to validate incoming HTTP requests with a variety of powerful validation rules.

There are following files will participate:

  • /resources/employee/create.blade.html – Used for display data.
  • /controllers/EmployeeController.php – This file will contain all actions method.

You can also check other recommended tutorials of Lumen/Laravel,

Laravel 9 Validation Example

Let’s begin the Laravel Validation Tutorial with a simple example on the server side. Client-side validation is also possible, but it is not recommended.

Create View file For Laravel validation

We’ll make a view file with an HTML form and elements, as well as a submit button for sending form data to the server. The laravel action method will validate the form post data against the validation rules.

If any of the validation rules fails, an exception will be given to the user with a correct error response. If all validation rules pass, your function will continue to run properly.

Create a new view file into the resources/views/employee/create.blade.php folder.

<form id="addEmployee" action="{{ route('employee.store') }}" method="POST">
    <input name="_token" type="hidden" value="{{ csrf_token() }}" /> <input name="user_id" type="hidden" value="{{ Auth::id() }}" /> <input name="add_form_validate" type="hidden" value="1" />
    <div class="modal-body">
        <div class="form-group {{ $errors->has('name') ? ' has-error' : '' }}">
            <label class="control-label">Employee Name</label> <input class="form-control" name="name" type="text" value="{{Request::old('name')}}" /> @if ($errors-&gt;has('name'))
            <span class="help-block"><strong>{{ $errors-&gt;first('name') }}</strong></span> @endif
        </div>
        <div class="form-group {{ $errors->has('salary') ? ' has-error' : '' }}">
            <label class="control-label">Employee Salary</label> <input class="form-control" name="salary" type="number" value="{{Request::old('salary')}}" /> @if ($errors-&gt;has('salary'))
            <span class="help-block"><strong>{{ $errors-&gt;first('salary') }}</strong></span> @endif
        </div>
        <div class="form-group {{ $errors->has('age') ? ' has-error' : '' }}">
            <label class="control-label">Employee Age</label> <input class="form-control" name="age" type="number" value="{{Request::old('age')}}" /> @if ($errors-&gt;has('age'))
            <span class="help-block"><strong>{{ $errors-&gt;first('age') }}</strong></span> @endif
        </div>
    </div>
    <div class="modal-footer"><button class="btn btn-info" type="submit">Add</button> <button class="btn btn-default" type="button" data-dismiss="modal">Cancel</button></div>
</form>

Create an action method to enter the employee’s information into the database. To validate form data, we’ll construct a validation rule. We will add below code into app/Http/Controllers/ EmployeeController.php file.

public function store()
{
	$rules = array(
		'name' => 'required|string|max:255',
		'salary' => 'required|is_integer()',
		'age' => 'required|is_integer()'
	);
	$params = $request->all();
	$validator = Validator::make($params, $rules);
	if ($validator->fails()) {
		$request->merge(array('add_form_validate' => 1));
		//print_r($request->all());die('jjj');
		$input['add_form_validate'] = '1';
		return redirect('employee.create')
					->withErrors($validator)
					->withInput();
	} else {

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

		flash()->success('The employee has been created successfully.');

		return redirect()->route('employee.index');  
	}	
}

As you can see, We have defined $validation rules and validate using laravel inbuilt validate class.

Leave a Reply

Your email address will not be published. Required fields are marked *