Im Durchschnitt wird dieses Tutorial Laravel Validation: A step-by-step guide mit 5 bewertet, wobei 1.0 die schlechteste und 5.0 die beste Bewertung ist. Es haben insgesamt 35 Besucher eine Bewertung abgegeben.
35 0

Laravel Validation: A step-by-step guide

from gridscale Team Coding Laravel

All great. You are an awesome laravel developer and developed a feature rich application. You claim to put all your efforts to code there. But now consider below scenario:

As it happens, users do not behave as you expected and fill out some fields wrongly. For example, a user wants to be extra nice, entered a currency symbol in amount field ($100) and got it saved. The fun will begin when your data store script will try to save this data to a numeric database field…run time errors.

Now if your application does not handle a scenario like the one above and similar others then hello to a land of mess and run time errors which you never wish to have. A robust app starts with the architecture of storing the right type of data from users and allowing them to input data with specific rules.

Today I show you need to know when getting started with validations in Laravel to avoid any scenario as mentioned above and to have a fool proof application.

Let me make it work for you and show how validation system in Laravel works with plain simple example. My effort here is to keep this tutorial easy to understand, implement and scale from here.

To make this tutorial not too complex, we are underlying only necessary code. Although you do not need to know everything about Laravel to go through this tutorial, I encourage you that you have some knowledge or reading related to Laravel and that would be:

  • Since the validation system in Laravel differs to a normal conventional one, you should know the architecture of MVC. This will help you to understand the flow of the code execution and which place is ideal to place the validation which I am going to discuss later in this article.
  • And if you are still in search of good source on learning Laravel then we recommend this article. You will get everything to get started with Laravel here and more.

Just to demonstrate – consider that you will have some user details to be saved to the DB with Laravel as framework. Consider example fields like username, phone, and email. You will have the validation for these fields but you will not limit it here. I will demonstrate all other types of validation you can have, where to place it, how to handle validation errors and more.

Your route, model, controller and view should look something like below:

Model [ Basically model logic talk to data]
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserDetails extends Model
{
protected $fillable = [
'name', 'phone','email','bio'
];
...
...
}

Now the above code should not bother you and understand that basically it holds the dataset of DB table for user details. Know more about Laravel models here.

Route [Handles all requests and and propagate response]
Route::resource(user_details, 'UserDetailsController');

The above single line of magic code is creating routes for all HTTP methods – be it Save, Update, Delete, etc. Route files are nothing but handling all user requests and responsible for sending across all responses from the application. Know how controllers would handle such routing here.

View [Basically blade template files that handles the user facing view, V of MVC]
@extends('layout.master')  // inherits master template 
@section('content')
<form method="POST" action="{{ url(‘user_details/store’) }}">
  User name:<br>
  <input type="text" name="username" value="">
  <br>
  Phone:<br>
  <input type="text" name="phone" value="">
<br>
Email:<br>
  <input type="text" name="email" value="">
  <br><br>
  <input type="submit" value="Submit">
</form> 
 @endsection

A simple form to send data in Laravel blade template. Code that you can see in action generates the URL or say the route that is needed for post methods to save data. Again, I am not complicating things here and want to stick to our motive – setting you on right path on Laravel validations only.

Controller   [snippet to save data] 
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\UserDetails;
….
….
public function store(Request $request)
    {
//validate the request
        UserDetails::create($request->all());
//
    }
….
….

You can see in the above code that all the request data that is coming is getting saved with UserDetails modal. You can find more about Laravel Eloquent ORM here.
Now if you can notice in the above controller snippet, it is commented to do task ‘validate request’. You got it right, this is the place where you will be doing some magic to validate requests. Magic since Laravel makes your life easy with coding and allows you to spend your energy where it’s needed – building logic and architecture.

Let me explain in a plain way. Your controller always inherits traits and methods for you to make the validation in Laravel. The method ‘Validate’ is all you need to know and implement, which will help you to lay down the rules and handling of the. Also, it will make sure that if the validation fails, it will redirect to your form with all validation error messages.

Let me show you how our previous controller method to store data would look like after implementing validations:

public function store(Request $request)
    {
$this->validate($request, [
        'username' => 'required|unique:userdetails|max:100,
        'phone' => 'required|numeric|max:10',
        'email' => 'required|email',
    ]);
 UserDetails::create($request->all());
//
    }

Expected complexity? Nah. With Laravel your life becomes easy, with coding at least.

Let me explain the code snippet for validations.

It applies the validate method and pass request data. Now, within options of this method you can lay down rules for the validation for desired form fields. Here in this case all three fields are required. You can see other options separated with the pipe sign. See the username field has a unique validation and it takes user details like the DB table name. That means it will check for the primary or unique index on the username field for you when you say ‘unique:userdetails’. Also, it checks for a valid email format in the email field. This is a plain example with sample fields, but Laravel offers wide range of validation rules like max and min length, various data format validations, allowed image types in case of attachment and many more. Check out here for complete set of validation rules.

If any of the rules laid down in the validation is breached, Laravel outputs an exception and gets you redirected to your input URL with error messages which you can display. For instance, you can can loop through all the error messages in the below way:

In your blade template:

@if($errors)  //laravel blade shorthand for php If tag 
foreach ($errors->all() as $message) {
   // your list of error message goes here
}
@endif

Above code should display all validation errors when they occur.
Or you may want to a show validation error message right next to a specific field – then it should go like this:

<div class="error">{{ $errors->first(‘username’) }}</div>

I have demonstrated how and where to put validation rules. To put them in the controller is best practice for all types of Laravel applications.
If applications are going to become complex and you have a penchant for clean and separate code, you can use ‘Form request validation’. In simple words – you can create request files which will hold rules to validate each request before reaching the controller.

First, you need to generate request files with an artisan command like:

php artisan make:request UserDetailsRequest
With the above command, you will have the request files in the app/Http/Requests directory.
There you can have your rules of validation (sample below):
public function rules()
{
    return [
        'username' => 'required|unique:userdetails|max:100,
        'phone' => 'required|numeric|max:10',
        'email' => 'required|email',
    ];
}

Your code for displaying validation errors remains the same as I have mentioned previously for the validation kept in the controller.

All great. You are an awesome laravel developer and developed a feature rich application. You claim to put all your efforts to code there. But now consider below scenario: As it happens, users do not behave as you expected and fill out some fields wrongly. For example, a user wants to be extra nice, entered […]

Schade, dass dir der Artikel nicht gefallen hat.
Was sollten wir deiner Meinung nach besser machen?

×

Developer?

Get the latest gridscale developer tutorials here.
And don’t worry - we won’t spam you