0 Shares 1587 Views

Laravel Form Request

In our Laravel projects, we will talk about the Form Request class that we use to increase the code readability and to perform more complex validation in requests. I’ll tell you through a book project. But first, let’s create routes.

  • Initially, it must look like this:
<code>

# route / api.phpRoute::group(['prefix' => 'book'], static function () {

Route::post('create', 'BookController@create');

Route::get('list', 'BookController@list');

Route::delete('delete', 'BookController@delete');

Route::put('update', 'BookController@update');

});

</code>

Now we create a Controller via Artisan CLI.

  • PHP artisan make:controller BookController

then we create our methods, which must look like this:

<code>

# app/Http/Controller/BookController

class BookController extends Controller

{

public function create()

{

}

public function list()

{

}

public function update()

{

}

public function delete()

{

}

}

</code>

first, let’s do a normal validation and then compare our codes. Let’s suppose we have created a book so that the information of the book is as follows.

  • The title of the book
  • Explained
  • Author
  • Publisher
  • Price
  • Number of pages
  • Publication Year
  • ISBN Number
  • Image Link
  • Language

Now let’s perform a verification and registration simulation based on this information. Now he sees it;

<code>

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Validator;

class BookController extends Controller

{

public function create(Request $request)

{

$validator = Validator::make($request->all(),[

'name' => 'required|string|max:255',

'slug' => 'required|string|max:255',

'description' => 'required|string|max:500',

'writer' => 'required|string|max:100',

'publisher' => 'required|string|max:100',

'price' => 'required|regex:/^\d+(\.\d{1,2})?$/',

'page_number' => 'required|numeric|min:1',

'edition_year' => 'required|numeric',

'isbn' => 'required|numeric|unique:blog,isbn',

'image' => 'required|string|max:255',

'lang' => 'required|string',

]);

if ($validator->fails()) {

return response()->json($validator->errors());

}else{

/**

* Other operations include database registration and so on.

*/

return response()->json('Book created.',200);

}

}

...

</code>

 

As we have seen, when the controls are very crowded and require more processing, or when we add our validation methods, we need to break down the code into short pieces and manage it from a single place. So let’s get to the main part now. Let’s create a class with Artisan CLI.

  • php artisan make:request BookCreateRequest

after running it you will see the app / Http / Request folder and the BookCreateRequest file under it. This file should look like this;

<code>

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class BookCreateRequest extends FormRequest

{

/**

* Determine if the user is authorized to make this request.

*

* @return bool

*/

public function authorize()

{

return false;

}

/**

* Get the validation rules that apply to the request.

*

* @return array

*/

public function rules()

{

return [

//

];

}

}

</code>

Let’s talk about the authorize method here. This part allows us to verify the request of the party. If you return “false Buradan as the value

403 return will be transmitted.

  • 403 | This action is unauthorized.

If we wanted to do this in the example above, it would write the validation process into a validation eg.

<code>

use Illuminate\Support\Facades\Auth;

class BookController extends Controller

{

public function create(Request $request)

{

if (Auth::check() && Auth::user()->isAdmin()) {

$validator = Validator::make($request->all(), [

'name' => 'required|string|max:255',

'slug' => 'required|string|max:255',

'description' => 'required|string|max:500',

....

</code>

etc. will be performing such operations. Auth and similar structures I will talk about in other articles, the current part is not here, as you can see is becoming increasingly complex. Best of all, let’s solve this in the new file we created. Let’s do the following in the BookCreateRequest class. First of all, let’s handle the verification part. Our file now looks like this.

<code>

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

use Illuminate\Support\Facades\Auth;

class BookCreateRequest extends FormRequest

{

/**

* Determine if the user is authorized to make this request.

*

* @return bool

*/

public function authorize() :bool

{

// Verification process

return (Auth::check() && Auth::user()->isAdmin());

}

....

</code>

Now let’s do the other verification process.

<code>

/**

* Get the validation rules that apply to the request.

*

* @return array

*/

public function rules()

{

return [

'name' => 'required|string|max:255',

'slug' => 'required|string|max:255',

'description' => 'required|string|max:500',

'writer' => 'required|string|max:100',

'publisher' => 'required|string|max:100',

'price' => 'required|regex:/^\d+(\.\d{1,2})?$/',

'page_number' => 'required|numeric|min:1',

'edition_year' => 'required|numeric',

'isbn' => 'required|numeric|unique:blog,isbn',

'image' => 'required|string|max:255',

'lang' => 'required|string',

];

}

</code>

after the last uploads, the whole file should look like this.

<code>

 

<?php


namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

use Illuminate\Support\Facades\Auth;

class BookCreateRequest extends FormRequest

{

/**

* Determine if the user is authorized to make this request.

*

* @return bool

*/

public function authorize() :bool

{

return (Auth::check() && Auth::user()->isAdmin());

}

/**

* Get the validation rules that apply to the request.

*

* @return array

*/

public function rules()

{

return [

'name' => 'required|string|max:255',

'slug' => 'required|string|max:255',

'description' => 'required|string|max:500',

'writer' => 'required|string|max:100',

'publisher' => 'required|string|max:100',

'price' => 'required|regex:/^\d+(\.\d{1,2})?$/',

'page_number' => 'required|numeric|min:1',

'edition_year' => 'required|numeric',

'isbn' => 'required|numeric|unique:blog,isbn',

'image' => 'required|string|max:255',

'lang' => 'required|string',

];

}

}

</code>

so we have separated and managed everything we use for verification, and now let’s use it in the Controller and examine the difference.

<code>

<?php

namespace App\Http\Controllers;

use App\Http\Requests\BookCreateRequest;

class BookController extends Controller

{

public function create(BookCreateRequest $request)

{

// Database registration and so on.

}

</code>

where we implement Dependency Injection in the create method and specify that it will receive a $ request of type BookCreateRequest. This means that the Request that we create directly runs and verifies that if there is a problem there is a direct return to the clientside and it does not continue to the Controller side (* I will explain the return types and message management in this article in another article) and consequently the Controller remains clean and improves readability. Let’s do a review before and after.

<code>

<?php

namespace App\Http\Controllers;use Illuminate\Http\Request;

use Illuminate\Support\Facades\Auth;

use Illuminate\Support\Facades\Validator;

class BookController extends Controller

{

public function create(Request $request)

{

if (Auth::check() && Auth::user()->isAdmin()) {

$validator = Validator::make($request->all(), [

'name' => 'required|string|max:255',

'slug' => 'required|string|max:255',

'description' => 'required|string|max:500',

'writer' => 'required|string|max:100',

'publisher' => 'required|string|max:100',

'price' => 'required|regex:/^\d+(\.\d{1,2})?$/',

'page_number' => 'required|numeric|min:1',

'edition_year' => 'required|numeric',

'isbn' => 'required|numeric|unique:blog,isbn',

'image' => 'required|string|max:255',

'lang' => 'required|string',

]);

if ($validator->fails()) {

return response()->json($validator->errors());

} else {

/**

* Other operations include database registration and so on.

*/

return response()->json('Book created.', 200);

}

}

}

....

</code>

and after;

<code>

<? php

namespace App\Http\Controllers;

use App\Http\Requests\BookCreateRequest;

class BookController extends Controller

{

public function create (BookCreateRequest $ request)

{

//Other operations include database registration and so on.

}

....

</code>

the difference can be seen very clearly.

Stay tuned for the next articles:

  • Return messages
  • Create a custom message
  • Special control structures
  • Authorization and so on. operations.

 

 

You may be interested

The Ultimate CDN (Content Delivery Network) Guide
CDN
1699 views
CDN
1699 views

The Ultimate CDN (Content Delivery Network) Guide

Nadia Benslimane - August 3, 2020

The Ultimate CDN Guide- Everything About CDN You probably know what CDN (Content Delivery Network) stands for. You may also be aware of its full definition, but…

The Essential CDN Glossary
CDN
7957 views
CDN
7957 views

The Essential CDN Glossary

Nadia Benslimane - November 21, 2019

Why Have We Decided To Create a CDN Glossary? Whether you are new to the world of CDN, or have been involved in it for years, there…

Lean Approaches In Technology Used By Medianova
How To
67 views
How To
67 views

Lean Approaches In Technology Used By Medianova

Selin Sezer - September 23, 2020

This Is How We Use Lean Approaches In Technology At Medianova Without being aware of the existence of many concepts, we enjoy the comfort these concepts bring…

Effects of the New-Generation Business World on Human Resources
Uncategorized
36 views
Uncategorized
36 views

Effects of the New-Generation Business World on Human Resources

Mujde Karakaya - September 22, 2020

We have been discussing lately how the business processes will be digitalized and due to the pandemic, we have witnessed that a process can digitalize even within…

E-commerce API Caching And Mobile Apps (Why You Need API Caching)
CDN
117 views
CDN
117 views

E-commerce API Caching And Mobile Apps (Why You Need API Caching)

Tushar Sonal - September 18, 2020

E-commerce API Caching And Mobile Apps Nowadays, it is typical for e-commerce platforms to use several different APIs to deliver wide-ranging functionality to their visitors. Application Programming…

Most from this category

The Ultimate CDN (Content Delivery Network) Guide
CDN
1699 views
1699 views

The Ultimate CDN (Content Delivery Network) Guide

Nadia Benslimane - August 3, 2020
The Essential CDN Glossary
CDN
7957 views
7957 views

The Essential CDN Glossary

Nadia Benslimane - November 21, 2019
This is WebP and This How To Use It
CDN
1199 views
1199 views

This is WebP and This How To Use It

Tushar Sonal - August 13, 2020