Save time by handling POST, PUT, and DELETE in a single FormRequest in Laravel 5
https://www.kerneldev.com

Save time by handling POST, PUT, and DELETE in a single FormRequest in Laravel 5

This article might seem stupid but I was tired of adding FormRequest for common HTTP verb (PUT, POST, DELETE) used in the controller.

Though separating these files might have their benefits in a large application where other checks are needed to be performed but it was cumbersome for me for small scale applications.

Let’s learn using an example:

Consider you have a CategoriesController like this:

 

You can create separate FormRequest (CreateCategoryFormRequest, UpdateCategoryFormRequest, DeleteCategoryFormRequest) files for every type of request, or if you're like me, you can create only one FormRequest file and handle every type of request within the file.

What I'd do next is create a FormRequest like this:

php artisan make:request CategoryFormRequest

this will generate the following class in the Requests directory of your Laravel application.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class CategoryFormRequest 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 [
//
];
}
}

As you can see, you get a plain class. Now I'd add a switch statement to handle different requests:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class CategoryFormRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
// an extra layer of security,
// you can check for user role and permission to check if
// user can do this particular task here,
// you can also skip it by return true;
if(auth()->check())
{
// I'm using Entrust for user role management
$user = auth()->user();
switch($this->getMethod)
{
case 'post':
case 'POST':
return $user->hasPermission('create-category');
case 'put':
case 'PUT':
return $user->hasPermission('update-category');
case 'DELETE':
case 'delete':
return $user->hasPermission('delete-category');
}
}
return false;
}

/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
switch ($this->getMethod())
{
// handle creates
case 'post':
case 'POST':
return [
'name' => 'required|unique:categories,name',
];

// Handle updates
case 'put':
case 'PUT':
return [
'category_id' => 'required|exists:categories,id',
'name' => [
'required',
Rule::unique('categories')->ignore(request('category_id))
];

// handle deletions
  case 'delete':
case 'DELETE':
return [
'category_id' => 'required|exists:categories,id'
];
}
// return empty array for other requests
return [
//
];
}
}

 This is it