Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 14

Laravel Request and Validation

Larave

STUDY GUIDE FOR MODULE NO. 4.3

Laravel Request and Validation

MODULE OVERVIEW

MODULE LEARNING OBJECTIVES

At the end of this module, students are expected to:


1. Explain the 2 approaches of instantiating a HTTP request
2. Learn how to retrieve form inputs using Laravel Request
3. Explain Laravel’s CSRF Protection
4. Implement Laravel Request and form validation

LEARNING CONTENTS (Overview of View)

Laravel Request

Laravel's Request is used to interact with the current HTTP request being handled by your
application as well as retrieve the input, cookies, and files that were submitted with the request. To
obtain an instance of the current HTTP request, you may include the Illuminate\Http\Request class
on your route.

Instantiate HTTP Request

1. Using Controller
<?php

Namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

Class UserController extends Controller {

Public function store (Request $request)


{
$name = request->input(‘name’);
}

2. Inside the Route closure

Use Illuminate\Http\Request;
Use App\Http\Requests;

PANGASINAN STATE UNIVERSITY 1


Laravel Request and Validation
Larave

Route::(‘/’, function (Request $request) {

});

Retrieving Input

The input values can be easily retrieved in Laravel. No matter what method was
used “get” or “post”, the Laravel method will retrieve input values for both the methods the same
way. There are two ways we can retrieve the input values.

 Using the input() method


 Using the properties of Request instance

Using the input() method

The input() method takes one argument, the name of the field in form. For example, if the form
contains username field then we can access it by the following way.

$name = $request->input('username');

Using the properties of Request instance

Like the input() method, we can get the username property directly from the request instance.

$request->username

CSRF Protection

CSRF refers to Cross Site Forgery attacks on web applications. CSRF attacks are the unauthorized
activities which the authenticated users of the system perform. As such, many web applications are
prone to these attacks.

Laravel offers CSRF protection in the following way −

Laravel includes an in built CSRF plug-in, that generates tokens for each active user session. These
tokens verify that the operations or requests are sent by the concerned authenticated user.

Implementation

The implementation of CSRF protection in Laravel is discussed in detail in this section. The
following points are notable before proceeding further on CSRF protection −

CSRF is implemented within HTML forms declared inside the web applications. You have to include
a hidden validated CSRF token in the form, so that the CSRF protection middleware of Laravel can
validate the request. The syntax is shown below −

PANGASINAN STATE UNIVERSITY 2


Laravel Request and Validation
Larave

<form method = "POST" action="/profile">

...

</form>

Form without CSRF token

Consider the following lines of code. They show a form which takes two parameters as input: email
and message.

<form>

<label> Email </label>

<input type = "text" name = "email"/>

<br/>

<label> Message </label> <input type="text" name = "message"/>

<input type = ”submit” name = ”submitButton” value = ”submit”>

</form>

The result of the above code is the form shown below which the end user can view − Contact Form

The form shown above will accept any input information from an authorized user. This may make
the web application prone to various attacks.

Please note that the submit button includes functionality in the controller section. The postContact
function is used in controllers for that associated views. It is shown below −

public function postContact(Request $request) {

return $request-> all();

Observe that the form does not include any CSRF tokens so the sensitive information shared as
input parameters are prone to various attacks.

Form with CSRF token

The following lines of code shows you the form re-designed using CSRF tokens −

<form method = ”post” >

{{ csrf_field() }}

PANGASINAN STATE UNIVERSITY 3


Laravel Request and Validation
Larave

<label> Email </label>

<input type = "text" name = "email"/>

<br/>

<label> Message </label>

<input type = "text" name = "message"/>

<input type = ”submit” name = ”submitButton” value = ”submit”>

</form>

The output achieved will return JSON with a token as given below −

"token": "ghfleifxDSUYEW9WE67877CXNVFJKL",

"name": "TutorialsPoint",

"email": "contact@tutorialspoint.com"

This is the CSRF token created on clicking the submit button.

Example

web.api

Route::get("/registration", [PostsController::Class, 'ipakita']);


Route::post("/registration/register", [PostsController::Class, 'postOutput']);

View

registration.blade.php

<html>
<head>
<title>Form Example</title>
</head>
<body>
<form action = "/registration/register" method = "post">
//using registration.php only
<input type = "hidden" name = "_token" value = "<?php echo csrf_token() ?>">

PANGASINAN STATE UNIVERSITY 4


Laravel Request and Validation
Larave

// or using blade template you may add the code below


// {{ csrf_field() }}

<table>
<tr>
<td>Name</td>
<td><input type = "text" name = "name" /></td>
</tr>
<tr>
<td>Position</td>
<td><input type = "text" name = "position" /></td>
</tr>
<tr>
<td>Organization</td>
<td><input type = "text" name = "org" /></td>
</tr>
<tr>
<td>Email</td>
<td><input type = "text" name = "email" /></td>
</tr>
<tr>
<td colspan = "2" align = "center">
<input type = "submit" value = "Register" />
</td>
</tr>
</table>

</form>
</body>
</html>

PostsController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class PostsController extends Controller


{
//
public function ipakita(){
return view('registration');
}

public function postOutput(Request $request){


$name = $request->input('name');
$position = $request->input('position');

PANGASINAN STATE UNIVERSITY 5


Laravel Request and Validation
Larave

$org = $request->input('org');
$email = $request->input('email');
echo 'Name: '.$name;
echo '<br>';
echo 'Position: '.$position;
echo '<br>';
echo 'Organization: '.$org;
echo '<br>';
echo 'Email: '.$email;
echo '<br>';

//Retrieve the name input field


$name = $request->name;
echo 'Name: '.$name;
echo '<br>';

}
}

Laravel Validation

Laravel provides several different approaches to validate your application's incoming data. It is most
common to use the validate method available on all incoming HTTP requests. Laravel includes a
wide variety of convenient validation rules that you may apply to data, even providing the ability to
validate if values are unique in a given database table.

Laravel Validation Rules

Laravel will always check for errors in the session data, and automatically bind them to the view if
they are available. The $errors variable will always be available in all of your views on every
request, allowing you to conveniently assume the $errors variable is always defined and can be
safely used. The following table shows all available validation rules in Laravel.

Available Validation Rules in Laravel

Accepted Active URL After (Date)

Alpha Alpha Dash Alpha Numeric

Array Before (Date) Between

Boolean Confirmed Date

Date Format Different Digits

Digits Between E-Mail Exists (Database)

Image (File) In Integer

IP Address JSON Max

MIME Types(File) Min Not In

Numeric Regular Expression Required

PANGASINAN STATE UNIVERSITY 6


Laravel Request and Validation
Larave

Required If Required Unless Required With

Required With All Required Without Required Without All

Same Size String

Timezone Unique (Database) URL

The $errors variable will be an instance of Illuminate\Support\MessageBag. Error message can


be displayed in view file by adding the code as shown below.
@if (count($errors) > 0)
<div class = "alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>@endif

The following list shows some Laravel validation rules:

#1) Before Or Equal (Date) – before_or_equal:date

This validation rule only allows using a value preceding or equal to the given date.

#2) Between – between:min,max

This validation rule only allows using a size between the given min and max.

#3) Date – date

This validation rule only allows using a valid, non-relative date according to the strtotime PHP
function.

#4) Date Format – date_format:format

Under this validation rule, the field must match the given format.

#5) Different – different:field

Under this validation rule, the field must have a different value than the field.

#6) Distinct – distinct

When working with arrays, under this validation rule, the field must not have any duplicate values.

#7) Email – email

Under this validation rule, the field must be formatted as an email address.

PANGASINAN STATE UNIVERSITY 7


Laravel Request and Validation
Larave

#8) Image (File) – image

Under this validation rule, the field must be an image (jpeg, png, bmp, gif, svg, or webp).

#9) Nullable – nullable

Under this validation rule, the field must be null.

#10) Numeric – numeric

Under this validation rule, the field must be numeric.

#11) Regular Expression – regex:pattern

Under this validation rule, the field must match the given regular expression.

#12) Required – required

Under this validation rule, the field must be present in the input data and not empty.

#13) Size – size:value

Under this validation rule, the field must have a size matching the given value.

#14) Sometimes – sometimes

This validation rule runs validation checks against a field only if that field is present in the input
array.

#15) URL – url

Under this validation rule, the field must be a valid URL.

Defining the Routes

use App\Http\Controllers\PostController;
Route::get('/registration/new', [PostController::class, 'ipakita']);
Route::post('/registration', [PostController::class, 'postOutput']);

Create Controller

<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class PostController extends Controller{
/**
* Show the form to create a new blog post.
*

PANGASINAN STATE UNIVERSITY 8


Laravel Request and Validation
Larave

* @return \Illuminate\View\View
*/
public function ipakita()
{
return view('registration');
}

public function postOutput(Request $request)


{
// Validate the form after submission
}}

Validation using Laravel Request

Form requests are custom request classes that encapsulate their own validation and authorization
logic. To create a form request class, you may use the make:request Artisan CLI command:

php artisan make:request StorePostRequest

The generated form request class will be placed in the app/Http/Requests directory.Each form


request generated by Laravel has two methods: authorize and rules.
The authorize method is responsible for determining if the currently authenticated user can perform
the action represented by the request, while the rules method returns the validation rules that
should apply to the request's data

/**
* Get the validation rules that apply to the request.
*
* @return array
*/public function rules(){
return [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
];}

/**
* Store a new blog post.
*
* @param \App\Http\Requests\StorePostRequest $request
* @return Illuminate\Http\Response
*/
public function store(StorePostRequest $request)
{
// The incoming request is valid...

// Retrieve the validated input data...


$validated = $request->validated();

PANGASINAN STATE UNIVERSITY 9


Laravel Request and Validation
Larave

Repopulating the Form

When Laravel generates a redirect response due to a validation error, the framework will
automatically flash all of the request's input to the session. This is done so that you may
conveniently access the input during the next request and repopulate the form that the user
attempted to submit.

To retrieve flashed input from the previous request, invoke the old method on an instance of
Illuminate\Http\Request. The old method will pull the previously flashed input data from the session:

$title = $request->old('title');

Laravel also provides a global old helper. If you are displaying old input within a Blade template, it
is more convenient to use the old helper to repopulate the form. If no old input exists for the given
field, null will be returned:

<input type="text" name="title" value="{{ old('title') }}">

Customizing the Validation

1. Using the Language File

The simplest and straightforward way to customize your validation error messages is through the
language file. Laravel by default ships with it, language (English) files. These files can be found in
resources/lang/en directory. For this tutorial, we are only concerned with validation.php file.

We can also specify custom validation messages for attributes:

PANGASINAN STATE UNIVERSITY 10


Laravel Request and Validation
Larave

// resources/lang/en/validation.php
'custom' => [
'email' => [
'required' => 'We need your email address also.',
],
]

If you scroll down to the very bottom the the validation.php language file, you something like:

PANGASINAN STATE UNIVERSITY 11


Laravel Request and Validation
Larave

Let's say we want the name attribute to be display as Full Name instead of name, we simply do:

// resources/lang/en/validation.php
'attributes' => [
'name' => 'Full Name'
]

2. Directly in the Code

Another way to implement custom validation error messages in your Laravel applications is to add
your custom error messages directly within your codes.

public function contact(Request $request)


{
$rules = [
'name' => 'required',
'email' => 'required|email',
'message' => 'required|min:5',
];

$customMessages = [
'required' => 'The :attribute field can not be blank.'
];

$this->validate($request, $rules, $customMessages);

// send contact details to email address

return back()->with("status", "Your message has been received, We'll get back to you shortly.");
}

PANGASINAN STATE UNIVERSITY 12


Laravel Request and Validation
Larave

Checkpoint-Activity

1. Create a registration form.See attached registration form. Validate and display the result
(registration form) in a Tabular format. Use Bootstrap 5 for the UI. Provide a custom message for
each of the validation rules.You can use regular expression for validating some of the user inputs.

Personal Information

First Name (max of 50 characters) (not empty)

Last Name (max of 50 characters) (not empty)

Sex Male Female


(not empty with the ff: format
Mobile Phone (0998-XXX-XXX) (0999-XXX-XXX) (0920-XXX-
XXX)

Tel No. Numeric values only

Birth date yyyy-mm-dd (format) (not empty) (valid date)

Address
(max 100 characters)
Email (valid email)

Website (valid URL )

User Account

Username 6-20 characters (not empty)

Password at least 6-12 characters (not empty)

Retype at least 6-12 characters (not empty)


Password
Create User

SUMMARY

In this module, you explored the use of Laravel request and implement validation to a form.

REFERENCES

Online learning materials

PANGASINAN STATE UNIVERSITY 13


Laravel Request and Validation
Larave

Validation - Laravel - The PHP Framework For Web Artisans

Laravel - Validation - Tutorialspoint

Laravel Forms And Validation Rules With Example (softwaretestinghelp.com)

Deep Dive Into Custom Validation Error Messages In Laravel ― Scotch.io

PANGASINAN STATE UNIVERSITY 14

You might also like