Professional Documents
Culture Documents
Elective 1 - SG 4.3
Elective 1 - SG 4.3
Larave
MODULE OVERVIEW
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.
1. Using Controller
<?php
Namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
Use Illuminate\Http\Request;
Use App\Http\Requests;
});
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.
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');
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 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 −
...
</form>
Consider the following lines of code. They show a form which takes two parameters as input: email
and message.
<form>
<br/>
</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 −
Observe that the form does not include any CSRF tokens so the sensitive information shared as
input parameters are prone to various attacks.
The following lines of code shows you the form re-designed using CSRF tokens −
{{ csrf_field() }}
<br/>
</form>
The output achieved will return JSON with a token as given below −
"token": "ghfleifxDSUYEW9WE67877CXNVFJKL",
"name": "TutorialsPoint",
"email": "contact@tutorialspoint.com"
Example
web.api
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() ?>">
<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;
$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>';
}
}
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 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.
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.
#8) Image (File) – image
Under this validation rule, the field must be an image (jpeg, png, bmp, gif, svg, or webp).
#9) Nullable – nullable
#10) Numeric – 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
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.
*
* @return \Illuminate\View\View
*/
public function ipakita()
{
return view('registration');
}
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:
/**
* 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...
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:
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.
// 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:
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'
]
Another way to implement custom validation error messages in your Laravel applications is to add
your custom error messages directly within your codes.
$customMessages = [
'required' => 'The :attribute field can not be blank.'
];
return back()->with("status", "Your message has been received, We'll get back to you shortly.");
}
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
Address
(max 100 characters)
Email (valid email)
User Account
SUMMARY
In this module, you explored the use of Laravel request and implement validation to a form.
REFERENCES